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

2019-01-08 22:05发布

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

标签: c++ packing
1条回答
乱世女痞
2楼-- · 2019-01-08 22:15

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.

查看更多
登录 后发表回答