c++packing

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


For example, I have a class,

class naive {
public:
    char a;
    long long b;
    char c;
    int d;
};

and according to my testing program, a to d are built one after another, like

a-------
bbbbbbbb
c---dddd

- means unused.

Why does not C++ make it tighter, like

ac--dddd
bbbbbbbb

Solution

  • 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.