Is there a legal way to define type with zero-size in C++? <eom> [duplicate]
Po开发者_如何学编程ssible Duplicate:
Can sizeof return 0 (zero)
Is there a legal way to define type with zero-size in C++?
No. Even a struct
with no members has a size.
No, a complete object cannot have a zero size. The reason is the following. Suppose that X is a class/struct with zero size. And you declare an array of X objects:
X arr[10];
the rule is that *(arr+3) must be the fourth element, but if sizeof(X)==0
then arr, arr+1 and all others will be equal!!!.
There is one case when a subobject can be of zero size, that is, a base-class subobject. Namely, if you derive class Y from X, where X is an empty class with size, say, 4, then the X subobject in Y may have 0 size.
HTH
The only legal way to make a type have zero size, is to make it the base of a type that has a size.
struct A { };
int cba = sizeof(A); // 1
struct B : A {
int32_t b;
};
int cbb = sizeof(B); // 4 - implying no storage for A.
C++ Standard.
1.8.5. Unless it is a bit-field (9.6), a most derived object shall have a non-zero size and shall occupy one or more bytes of storage. Base class sub-objects may have zero size. An object of POD type (3.9) shall occupy contiguous bytes of storage.
9.6.2. A declaration for a bit-field that omits the identifier declares an unnamed bit-field. Unnamed bit-fields are not members and cannot be initialized. As a special case, an unnamed bit-field with a width of zero specifies alignment of the next bit-field at an allocation unit boundary. Only when declaring an unnamed bit-field may the constant-expression be a value equal to zero.
精彩评论