Tail pad optimization, cache friendlyness and C++ interrop

Sean Cavanaugh via Digitalmars-d digitalmars-d at puremagic.com
Sat Jun 14 21:35:51 PDT 2014


On 6/11/2014 8:56 AM, Remo wrote:
>
> This is pretty strange behavior.
> At least on Windows I can not confirm this.
> Visual Studio 2013, Intel Compiler and Clang for windows have the same
> consistent behavior here.
>
> private  do NOT affect struct size.
>
> But there is a parameter in Visual Studio that will affect it called
> "Struct Member Alignment"
> http://msdn.microsoft.com/en-us/library/xh3e3fd0.aspx
>
> 1 Byte (/Zp1)  sizeof(S1)=5,  sizeof(S2)=6
> 2 Byte (/Zp2)  sizeof(S1)=6,  sizeof(S2)=8
> 4 Byte (/Zp4)  sizeof(S1)=8,  sizeof(S2)=12
> 8 Byte (/Zp8)  sizeof(S1)=8,  sizeof(S2)=12   this is the default.
>
> Of course the same can be done with #pragma pack(?) .
>
> There is also __declspec(align(?)) and in C++11  alignas(?) but its
> behavior is different from #pragma pack(?) .
>
>

For inheritance I've seen gcc and clang allow the inheriting to go into 
the tail padding of the previous class in the hierarchy, technically 
legal but always gives me scary thoughts before going to sleep at night.

MSVC pads up the classes to the alignment size and inheritance starts 
from there, a bit wasteful but far safer.

struct foo  { int x; char y; };
struct bar : public foo { char z; }

sizeof(foo == 8);
sizeof(bar == 8); // clang and gcc on linux
sizeof(bar == 12); // msvc

The windows case is generally safer as memset(&class, 0, sizeof(class)) 
won't clobber inherited members, but its also not supposed to be legal 
to do things like memsetting anything that fails is_pod etc in c++, 
however since nearly all code I've worked with has constructors is_pod 
is useless and people just memset struct-like objects without a care int 
he world, which can be fun when porting :)




More information about the Digitalmars-d mailing list