alignas() effect on sizeof() - mandatory?
Asked Answered
Z

1

5

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?

Zink answered 17/5, 2020 at 18:29 Comment(5)
I remember having this discussion with my programming instructor. IIRC, since arrays are required to have no gaps between elements, structures must be padded to make their size a multiple of the alignment.Evania
What would foo f[10]; do if it wouldn't affect the size that way?Saccule
"...When applied to a class type, the result is the size of an object of that class plus any additional padding required to place such object in an array...." source: en.cppreference.com/w/cpp/language/sizeofMonosyllable
@RichardCritten: So, it is mandatory then?Zink
That's my understanding but don't have a Standard reference to hand.Monosyllable
B
7

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.

Bercy answered 17/5, 2020 at 18:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.