empty base class optimization

后端 未结 3 589
借酒劲吻你
借酒劲吻你 2021-01-02 07:52

Two quotes from the C++ standard, §1.8:

An object is a region of storage.

Base class subobjects may have zero size.

I don\'t

3条回答
  •  死守一世寂寞
    2021-01-02 08:25

    C++ does not allow an object of size zero, because every object must have a unique memory address. So if you have:

    struct empty {};
    
    // ...
    
    empty myempty;
    empty* ptr = &myempty;
    

    then ptr must be pointing to a unique memory address. The standard states the minimum size for an object is 1 byte for this purpose. Similarly, allocations of size 0 are allowed, and return a valid pointer, even if writing to that pointer is not allowed (this works for malloc(0), and new empty returns a pointer to one byte, since sizeof(empty) == 1).

    If I derive from empty like so:

    struct derived : public empty
    {
        int data;
    }
    

    There is no longer any point in the base class empty occupying one byte, because all derived will have a unique address due to the data member. The quote "Base class subobjects may have zero size" is present to allow, in this case, for the compiler to not use any space for empty, such that sizeof(derived) == 4. As the title states, it's just an optimization, and it is perfectly legal for the empty part of derived to occupy zero space.

提交回复
热议问题