为什么 C++使结构更紧密?
例如,我有一个class
,
class naive {
public:
char a;
long long b;
char c;
int d;
};
根据我的测试程序,a
到d
是依次构建的,就像
a-------
bbbbbbbb
c---dddd
-
表示未使用。
为什么 C++ 不让它更紧,比如
ac--dddd
bbbbbbbb
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
标准要求类和结构成员按照声明的顺序存储在内存中。因此,在您的示例中,
d
不可能出现在b
之前。此外,大多数体系结构更喜欢多字节类型在 4 或 8 字节边界上对齐。因此,编译器所能做的就是在类成员之间留下空的填充字节。
您可以通过自己按大小顺序对成员重新排序来最小化填充。或者您的编译器可能有一个#pragma pack 选项或类似的选项,它将寻求最小化填充,但可能会牺牲性能和代码大小。阅读您的编译器的文档。
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 beforeb
.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.