Structure alignment changes when a constructor or destructor is added
Marc Glisse
marc.glisse@inria.fr
Tue Dec 6 23:22:00 GMT 2011
On Tue, 6 Dec 2011, Jonathan Wakely wrote:
> On 6 December 2011 20:59, Bruce Fraser wrote:
>> The following code was compiled with g++ 4.1.2 and again with g++
>> 4.6.2 on 64-bit Linux (more details at the end). Â Note that S1 and S3
>> have identical data members. Â S1 has a constructor defined, S3 does
>> not. Â S2 inherits from S1 and S4 inherits from S2. Â The size and
>> layout SHOULD be the same, but it is not as you can see from the
>> output.
>
> For C++98 / C++03 there are no guarantees about class layout except
> for POD types, and the presence of base classes and user-defined
> constructors prevents your types being PODs.
>
> C++11 provides the more fine-grained concept of a standard-layout
> struct, but even then I don't think there's any guarantee your S2 and
> S4 will have the same layout.
But g++ doesn't use a random layout, it (mostly) follows:
http://sourcery.mentor.com/public/cxx-abi/abi.html
so it makes sense to look at whether the layouts should be the same.
It seems to define the layout differently depending on whether a type is
POD (in the C++03 sense).
In particular, I note: "the C++ standard requires that compilers not
overlay the tail padding in a POD", but the ABI doesn't seem to impose any
such restriction on non-PODs.
It does look peculiar that this incites you to artificially make your
types non-POD for a more compact layout...
--
Marc Glisse
More information about the Gcc-help
mailing list