Alignment: The .alignof Property
By default, every object is placed at memory locations that are multiples of an amount specific to the type of that object. That amount is called the alignment of that type. For example, the alignment of
int is 4 because
int variables are placed at memory locations that are multiples of 4 (4, 8, 12, etc.).
Alignment is needed for CPU performance or requirements because accessing misaligned memory addresses can be slower or cause a bus error. In addition, certain types of variables only work properly at aligned addresses.
.alignof property of a type is its default alignment value. For classes,
.alignof is the alignment of the class variable, not the class object. The alignment of a class object is obtained by
The following program prints the alignments of various types: