When dealing with performance or external libraries sometimes you need to precisely control byte layout of your data structures.
There are several topics related to this subject:
- alignment: specify how many bytes should be allocated for the structure or variable & where it should start (offset optimization for cache)
- padding: specify additional bytes in order to start next variable at cache-friendly position
- reordering: organize structure attributes so the padding is not required or is minimal
- bitfields: pack several data structure attributes into one or more bytes
Reordering usually is done by sorting attributes by size (from largest to smallest). This ensures that automatic padding is minimal.
- The Lost Art of C Structure Packing - Eric S. Raymond
- C++ standard
- alignas - requires C++11, cppreference.com, see also "std::align", "alignof", "aligned_storage"
- C++ Language Features Tutorial #60 - alignof, alignas, sizeof - video tutorial by CodeAcademy.cc
- Visual C++:
- align (C++) - msdn
- Alignment and size of C/C++ basic and structure types (part of ABI) - Binglong's space
- pragma pack - msdn
- Why you shouldn’t use attribute((packed)) - Roland’s Blog
- Lesson 21. Pattern 13. Data alignment - viva64.com
- Padding and Rearranging Structure Members - Dan Saks, 2012
- Data Structure Alignment in C++ on x86 and x64 Machine - Xathrya Sabertooth, 2015