问题
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