C++ sizeof wrapper class

2020-04-02 08:53发布

问题:

Suppose I have a class A that does not inherit from anything, has no virtual methods, and has exactly one variable of type T. Does C++ guarantee sizeof(A) == sizeof(T)?

EDIT:

Also if T were a composite type, would it make a difference?

回答1:

No, it might be more than sizeof(T) due to padding.



回答2:

I don't think it explicitly guarantees it, but I don't think it would ever be different.



回答3:

I think C++ should guarantee sizeof(A) == sizeof(T).

Consider bellow situation, C++ should make it works just like in C:

A a[10];
T t[10];

A * ap = (A *) t;
T * tp = (T *) a;

memcpy(ap, tp, sizeof(*ap));


标签: c++ class sizeof