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
?
Microsoft Specific The extended attribute syntax for specifying storage-class information uses the __declspec keyword, which specifies that an instance of a given type is to be stored with a Microsoft-specific storage-class attribute listed below.
Structure padding is a concept in C that adds the one or more empty bytes between the memory addresses to align the data in memory.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With