问题
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
回答1:
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.
来源:https://stackoverflow.com/questions/6730664/why-doesnt-c-make-the-structure-tighter