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
Program output.
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
alignas(16) int x{}, y{};
does it mean it would have int as 16 bytes and not, say, 32 ?
x and y will be spaced 16 bytes apart
yeah. for a sec I mixed bits and bytes
all good. thanks!
forget about it. I mixed bits and bytes
it is 16 bytes instead of 4 bytes
it’s not. it stays sizeof(int), it just that it is aligned in memory differently. it DOES NOT change its size.
if i recall my white book correctly, int x:0 would cause the next field to be aligned on an int boundary.
What are the possible values I can write inside alignas(_)? Does alignas (4096) make sense?