问题
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