Consider the following struct:
struct alignas(8) Foo {
char data[8];
};
Is it guaranteed by the Standard that sizeof(Foo) == 8?
From a layman's point of view, it should be true, because 8 chars don't need any padding to have an alignment of 8.
And it seems to be true in practice on GCC, Clang, and MSVC (live demo).
However, padding and alignment is a tricky business, and I couldn't find any information that strictly forbids implementations from adding extraneous padding - i.e. sizeof(Foo) == 16 might be possible too?
I've found the following so far:
sizeof(char[8]) == 8is guaranteed (see here), thussizeof(Foo) >= 8)Foodoes not have leading padding, since it is a standard layout type (see here)- At least one more knowledgeable person - the author of
std::bit_cast- apparently believes there is no padding - see this article
(Interestingly, if this fact is untrue, it would seem to imply that structs can have arbitrarily large size, which is a bit strange.)