Will sizeof always be a multiple of alignof?
Asked Answered
S

1

9

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

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

Scutch answered 27/1, 2019 at 2:13 Comment(5)
Off-topic, but can you give an example where it matters?Omeara
@L.F. - placing an array of Type into memory you already own, if this is false, sizeof cannot be used as the stride between objects since later objects will align incorrectlyScutch
That's a good point. =.=Omeara
Yes, this follows from the properties of array types Type[N] (namely their size and lack of internal padding).Horrorstruck
@Anne I'm not sure, but I think it is. For example, see this, it manually constructs objects by the stride of sizeof(Tracer).Omeara
H
7

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.

Honolulu answered 27/1, 2019 at 4:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.