How does `__declspec(align(#))` work?

NPS picture NPS · Aug 10, 2013 · Viewed 15.3k times · Source

Yes, I have read this: http://msdn.microsoft.com/en-us/library/83ythb65.aspx But it's not clear to me. First of all, __declspec(align(#)) makes every object (in a structure) declared with it start at an aligned offset. That part is clear. The aligment is also 'inherited' by the structured the object is in. But it doesn't change the object's size, does it? Precisely, why does sizeof() in this code:

__declspec(align(32)) struct aType {int a; int b;};
sizeof(aType);

return 32?

Answer

Mats Petersson picture Mats Petersson · Aug 10, 2013

The size of the object is used to calculate offsets in arrays and when you use pointers, so sizeof(x) must always be a multiple of the alignment value. In this case, 1 x 32. But if you have __declspec(align(32)) struct aType {int a[12]; };, then the size would be 2 x 32 = 64, since sizeof(a) is 12 x 4 = 48. If we change it to align to 4, 8 or 16, it would be 48.

The way it actually works is that the compiler adds an unamed padding member after the named members of the structure, to fill the structure to it's alignment size.

If it didn't work this way, something like:

 aType *aPtr = new aType[15]; 

 aPtr[12].a = 42; 

wouldn't work right, since the compiler will multiply 12 by sizeof(aPtr) to add to aPtr internally.