Why doesn’t C++ make the structure tighter?

Class and struct members are required by the standard to be stored in memory in the same order in which they are declared. So in your example, it wouldn’t be possible for d to appear before b.

Also, most architectures prefer that multi-byte types are aligned on 4- or 8-byte boundaries. So all the compiler can do is leave empty padding bytes between the class members.

You can minimize padding by reordering the members yourself, in increasing or decreasing size order. Or your compiler might have a #pragma pack option or something similar, which will seek to minimize padding at the possible expense of performance and code size. Read the docs for your compiler.

Leave a Comment