Adding a default constructor to a base class changes sizeof() a derived type [duplicate]

此生再无相见时 提交于 2019-12-19 01:10:07

问题


I tend to think I have a pretty good grasp of C++ internals and memory layouts, but this one has me baffled. I have the following test code:

#include <stdio.h>

struct Foo
{
    //Foo() {}
    int x;
    char y;
};

struct Bar : public Foo
{
    char z[3];
};

int main()
{
    printf( "Foo: %u Bar: %u\n", (unsigned)sizeof( Foo ), (unsigned)sizeof( Bar ) );
}

The output is reasonable:

Foo: 8 Bar: 12

However, this is the very odd part, if I uncomment that simple default constructor on Foo(), the sizeof( Bar ) changes! How can the addition of a ctor possibly change the memory layout of these classes?

Foo: 8 Bar: 8

Compiled using gcc-7.2


回答1:


GCC follows the Itanium ABI for C++, which prevents the tail-padding of a POD being used for storage of derived class data members.

Adding a user-provided constructor means that Foo is no longer POD, so that restriction does not apply to Bar.

See this question for more detail on the ABI.



来源:https://stackoverflow.com/questions/47914612/adding-a-default-constructor-to-a-base-class-changes-sizeof-a-derived-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!