问题描述
该程序:
struct alignas(4) foo {};
int main() { return sizeof(foo); }
返回4,GCC 10.1和clang 10.1,icc 19.0.1.
returns 4, with GCC 10.1 and clang 10.1, and icc 19.0.1 .
这让我感到疑惑-是否必须强制 alignas()
这样影响 sizeof()
?即将尺寸增加到超出结构最初尺寸的尺寸?或者-这种更改只是实现的特权吗?
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?
推荐答案
是的.类的大小是根据该类型数组的元素之间的距离定义的.数组元素之间没有填充(填充在类型之内,因此在大小的一部分之内).如果大小小于对齐方式,则相邻数组元素将无法满足该对齐方式.
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.
大小必须至少与对齐方式相同,并且必须是对齐方式的倍数,并且对齐方式始终是2的幂.
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.
这篇关于alignas()对sizeof()的影响-强制性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!