Before modern C++ the only way to align variables or structures on a given byte boundary was to inject padding; to align a struct to 16 bytes you had to do this:

Not any more! Modern C++ introduced a keyword just for that: alignas (read more about it here). Now you can specify struct’s alignment like this:

This can be of great help when dealing with constructive or destructive interference of L1 cache lines. You can also space local variables apart, as well as struct/class members. Here’s a complete example (alignas.cpp):

sizeof(Old): 16
sizeof(New): 16
Address of ‘x’      : 0x7ffee4a448c0
Address of ‘y’      : 0x7ffee4a448d0
Address of ‘z’      : 0x7ffee4a448e0
Distance ‘x’ to ‘y’ : 16
Distance ‘y’ to ‘z’ : 16
sizeof(Empty)  : 1
sizeof(Empty64): 64
sizeof(Full): 64

Program output.

7 Replies to “Data alignment the C++ way”

  1. if i recall my white book correctly, int x:0 would cause the next field to be aligned on an int boundary.

Leave a Reply