Consider this simple program
#include <iostream>
struct A
{
int x1234;
short x56;
char x7;
};
struct B : A
{
char x8;
};
int main()
{
std::cout << sizeof(A) << ' ' << sizeof(B) << '\n';
return 0;
}
This prints 8 12
. Even though B
could be packed into 8 bytes without breaking alignment requirements, instead it takes up a greedy 12 bytes.
It would be nice to have sizeof(B) == 8
, but the answer to
Is the size of a struct required to be an exact multiple of the alignment of that struct? suggests that there isn't a way.
I was therefore surprised when the following
struct MakePackable
{
};
struct A : MakePackable
{
int x1234;
short x56;
char x7;
};
struct B : A
{
char x8;
};
printed 8 8
.
What is going on here? I suspect that standard-layout-types have something to do with it. If so, then what is the rationale for it causing the above behaviour, when the only purpose of that feature is to ensure binary-compatibility with C?
EDIT: As others have pointed out this is ABI or compiler specific, so I ought to add that this behaviour was observed on x86_64-unknown-linux-gnu with the following compilers:
- clang 3.6
- gcc 5.1
I have also noticed something strange from clang's struct dumper. If we ask for the data size without tail padding ("dsize"),
A B
first 8 9
second 7 8
then in the first example we get dsize(A) == 8
. Why is this not 7?