为什么C ++不会使结构更紧凑? [英] Why doesn't C++ make the structure tighter?

查看:170
本文介绍了为什么C ++不会使结构更紧凑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个 class

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

根据我的测试程序, a d 是一个接一个建立的,例如

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

- p>

为什么C ++不够紧凑,例如

 
ac - dddd
bbbbbbb


解决方案

标准需要类和结构体成员存储在内存中它们被声明的顺序相同。因此,在您的示例中, d 不可能出现在 b 之前。



此外,大多数架构喜欢多字节类型在4或8字节边界对齐。所以编译器可以做的是在类成员之间留空填充字节。



您可以通过自己重新排序成员,以增加或减少大小顺序来最小化填充。或者你的编译器可能有一个 #pragma pack 选项或类似的东西,这将寻求最小化填充,尽可能牺牲性能和代码大小。阅读您的编译器的文档。


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

解决方案

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.

这篇关于为什么C ++不会使结构更紧凑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆