C++ : How can I know the size of Base class SubObject?

后端 未结 3 1255
眼角桃花
眼角桃花 2020-12-19 19:08

.

Here I was discussing Empty Base Optimization, and MSalters made this interesting comment:

No class can ever have sizeof(Class)==0, empty

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-19 19:48

    The minium size of an object is 1:

    class X {};
    sizeof(X) >= 1
    

    But a derived class does not need to allocate room for this space if it is not used:

    class Y : public X {};
    sizeof(Y) >= 1
    

    So even though the class X by itself takes up 1 byte this is not translated to the parent class. So from Y's perspective the class X takes up 0 bytes.

    So here we can say that the compiler has optimizes away the base class (though technically it has done nothing. We just need to enforce the rule that no object has zero size).

    int main()
    {
        std::cout << sizeof(X) << ":" << sizeof(Y) << "\n";
    }
    

    Generates the following output:

    > ./a.exe
    1:1
    >
    

    The reason a class must have a size greater than zero is so that the address of every object is unique. If the compiler allowed a class to have zero size then there is a potential easy bug where multiple variables (objects) all had the same memory address (as they all had zero size). The simple rule to get around this potential problem is that all objects must have a non zero size.

    Summary:

    size_of_type(X) = size_of_type(base) + sum(size_of_type(members)) + padding + (extra stuff like vtable pointer etc);
    
    
    sizeof() = min(1, size_of_type())
    

提交回复
热议问题