Will sizeof always be a multiple of alignof?

孤人 提交于 2020-12-30 06:51:30

问题


Is sizeof(Type) always divisible by alignof(Type)

such that this statement will always be true? sizeof(Type) % alignof(Type) == 0


回答1:


Yes, sizeof(Type) % alignof(Type) == 0 is true for all class types.

The standard draft says:

[dcl.array] ... An object of array type contains a contiguously allocated non-empty set of N subobjects of type T.

[expr.sizeof] ... When applied to a class, the result is the number of bytes in an object of that class including any padding required for placing objects of that type in an array.

In order for every element of an array to be aligned, the distance between two adjacent elements must be a multiple of the alignment. sizeof is defined to be this distance.

Interestingly, for fundamental types other than narrow character type, sizeof is just implementation defined:

[expr.sizeof] ... The result of sizeof applied to any other fundamental type (6.7.1) is implementation-defined.

That said, I've never seen a system where the size of a fundamental type hasn't been a multiple of its alignment. They have to be aligned in an array as well after all.



来源:https://stackoverflow.com/questions/54384522/will-sizeof-always-be-a-multiple-of-alignof

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