Structure alignment in C++

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.

Generic introduction

Structure alignment

Tutorials

Padding

Bitfields

Share

follow