alignas() effect on sizeof() - mandatory?

此生再无相见时 提交于 2021-01-27 15:40:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!