Data alignment the C++ way
source link: https://vorbrodt.blog/2019/04/06/data-alignment-the-c-way/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Data alignment the C++ way
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): 64Program output.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK