问题
This program:
struct alignas(4) foo {};
int main() { return sizeof(foo); }
returns 4, with GCC 10.1 and clang 10.1, and icc 19.0.1 .
That makes me wonder - is it mandatory for alignas()
to affect sizeof()
this way? i.e. increase the size beyond what the structure would originally be sized at? Or - is this change just the implementation's prerogative?
回答1:
is it mandatory for alignas() to affect sizeof() this way? i.e. increase the size beyond what the structure would originally be sized at?
Yes. Size of a class is defined in terms of distance between elements of an array of that type. There is no padding between elements of an array (except for padding that is within the type and therefore part of the size). If size was less than alignment, then it would not be possible for adjacent array elements to satisfy that alignment.
Size must be at least as much as alignment, and it must be a multiple of the alignment, and alignments are always powers of two.
来源:https://stackoverflow.com/questions/61856747/alignas-effect-on-sizeof-mandatory