When the Structs Align ... and When They Don't
summary
Explains C++ alignment rules and tools like alignas and operator new(alignment), shows that misaligned placement new is undefined but x86 usually works while many embedded CPUs fault, and that UBSanitizer flags it. Demonstrates pragmatic fixes: reorder fields, use pragma pack to match external layouts, or pad for cache lines. Gives benchmarks: baseline 39.8 ns, unaligned ~80% slower, atomics ~10x slower, atomic unaligned is 5000x slower; padding to 64 bytes avoids false sharing and yields ~33% (or ~12% in a different test) speedups.
AI-written summary · about
chapters (19)
- 0:00Introduction and music analogy
- 4:45Speaker introduction
- 5:27C++ alignment rules
- 6:10Demo of alignment in C++
- 8:41ABI and stack alignment
- 9:46Dynamic memory alignment
- 11:10Breaking alignment rules
- 13:38Alignment in practice
- 15:03x86 alignment specifics
- 16:49Struct padding example
- 17:51Reordering struct members
- 18:13Pragma pack for alignment
- 19:37SIMD and alignment
- 21:00Cache lines and performance
- 22:28Benchmarking alignment impact
- 24:59False sharing in multithreading
- 26:46Bottom line on alignment
- 27:52When to use pragma pack
- 28:15Summary and conclusion
