开发者

sizeof() problems with empty class inheritance

#include <stdio.h> 

class X 
{
};

class Y
{
     // long x; // case A)
     // X x;    // case B)
};

class Z : public Y, public X
{
};

int main() {
     Z z;
     printf("%d %d %d\n", 
        sizeof(Z), sizeof(Y), (cha开发者_JAVA技巧r*)static_cast<X*>(&z) - (char*)&z);
     return 0;
}

Why is the output as follows after uncommenting either case A or case B:

A: 4 4 4

B: 2 1 2

Why is sizeof(Y) != sizeof(Z) in case B), but is equal in case A). Can anyone explain?


My memory is vague on this, but I think it's because the two X sub-objects of Z (the base class X and Y::x) must have different addresses.


Empty classes still are required to have a size of at least 1. But that doesn't mean that they have to impart that size to their sub-classes.


I encountered a similar problem on empty base class problem and found the explanation.

ISO/IEC 14882:2003 10-5

A base class subobject may be of zero size (clause 9); however, two subobjects that have the same class type and that belong to the same most derived object must not be allocated at the same address (5.10).

this means if object of Y has two subobjects of X, then both X MUST have different address(they must be 2 different objects with different address).

BTW, empty base class doesn't have to be 0 sized(it says MAY BE) until C++11, which claims it as required, more reference: http://en.cppreference.com/w/cpp/language/ebo


Just a little addition to your code:

#include <stdio.h>

class X
{
};

class Y
{
    // long x; // case A)
    public:
        X x;    // case B)
};

class Z : public Y, public X
{
};

int main() {
    Z z;
    printf("%d %d %d\n", sizeof(Z), sizeof(Y), (char*)static_cast<X*>(&z) - (char*)&z);

    printf("%p %p %p %p\n", &z, static_cast<Y*>(&z), static_cast<X*>(&z), &z.x);

    return 0;
}

In my machine I get:

2 1 1
0x7fff8876fcb0 0x7fff8876fcb0 0x7fff8876fcb1 0x7fff8876fcb0
   ^^Z             ^^Y             ^^X            Z::x

So, the two bytes are taken by X objects. One is the base class, the other is the one present in Y.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜