I wrote following code and tested it on gcc:
// firstly some platform-specific workarounds
#if _MSC_VER
#define ALN_BEGIN(x) __declspec(align(x))
#define ALN_END(x)
#define alignof(x) __alignof(x)
#else
#define ALN_BEGIN(x)
#define ALN_END(x) __attribute__((aligned(x)))
#define alignof(x) __alignof__(x)
#endif
// struct have three 4-byte members, but aligned at 32 byte
ALN_BEGIN(32) struct Foo
{
float a;
float b;
float c;
} ALN_END(32);
// show its size and alignment
int main(int argc, char** argv)
{
printf("size %d, alignment%d\n", sizeof(Foo), alignof(Foo));
}
When I compile it using gcc and run, although Foo only has 12 bytes for all its members, sizeof(Foo)
got 32 which is alignment size. So does the size expansion is according to language standard (which is reliable) or it is only a feature for GCC?
I'm making an object pool class, so I have to precisely work with type size and alignment.
Yes, this is consistent with the standard. sizeof (X)
is basically defined as the offset in bytes between the starting addresses of two consecutive X
objects in an array. If such objects cannot follow each other tightly due to alignment restrictions, sizeof
increases accordingly.
Quoting C++14, 5.3.3/2:
... When applied to a class, the result is the number of bytes in an object of that class including any padding required for placing objects of that type in an array. ... When applied to an array, the result is the total number of bytes in the array. This implies that the size of an array of n elements is n times the size of an element.
(Emphasis mine)
The result of sizeof
, for any type (except char
types, which have size 1
by definition), is implementation defined, and is affected by alignment. However, if
sizeof(float)
is 4
;floats
; ANDthen you can expect the behaviour you see.
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