Today I Learned that in C++, alignment behaves a bit differently for built-in types and class types. For many built-in types on mainstream platforms, alignment often matches the size of the type. For example:
alignof(int) == sizeof(int); // often true
alignof(double) == sizeof(double); // often true
However, this is not a general rule required by the language. The alignment of a type is implementation-defined.
For structs and classes, alignment depends on their members. In practice, it is at least as strict as the most strictly aligned member, and on most platforms it is equal to that member’s alignment. For example:
struct A {
char c;
int i;
};
static_assert(alignof(A) >= alignof(int));On common platforms where int is 4 bytes, A usually occupies 8 bytes: 1 byte for char, 3 bytes of padding, and 4 bytes for int.
The reason is that each object has to be placed at an address that satisfies its alignment requirement. This helps the CPU access the data efficiently. For types such as double, that often means an address divisible by 8 on common platforms. For example, on some CPUs, reading an 8-byte value that crosses an 8-byte boundary may require two internal memory reads instead of one. If the data is misaligned, the hardware may need extra work to read it, and on some architectures it can even trap.
Structs and classes follow the same idea: their alignment must be strong enough for all of their members, and their size is usually rounded up to a multiple of that alignment so that arrays of the type are laid out correctly.
“Live as if you were to die tomorrow. Learn as if you were to live forever.” - Mahatma Gandhi