C++中的结构填充 [英] Struct padding in C++

查看:33
本文介绍了C++中的结构填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在 C++ 中有一个 struct,有没有办法安全地将它读/写到跨平台/编译器兼容的文件中?

If I have a struct in C++, is there no way to safely read/write it to a file that is cross-platform/compiler compatible?

因为如果我理解正确的话,每个编译器都会根据目标平台填充"不同的内容.

Because if I understand correctly, every compiler 'pads' differently based on the target platform.

推荐答案

没有.这是不可能的.这是因为缺乏二进制级别的 C++ 标准化.

No. That is not possible. It's because of lack of standardization of C++ at the binary level.

Don Box 写道(引用自他的书 基本 COMCOM As A Better C++)

Don Box writes (quoting from his book Essential COM, chapter COM As A Better C++)


一旦做出决定将 C++ 类作为 DLL 分发,一个面临着最根本的问题之一C++的弱点,即缺乏二进制级别的标准化.尽管 ISO/ANSI C++ 草案工作文件试图编纂哪些程序将编译以及什么运行它们的语义效果将是,它没有尝试标准化C++ 的二进制运行时模型.这第一次这个问题会变成明显的是当客户尝试链接时针对 FastString DLL 的导入库来自一个 C++ 开发环境 other比用于构建FastString DLL.

C++ and Portability


Once the decision is made to distribute a C++ class as a DLL, one is faced with one of the fundamental weaknesses of C++, that is, lack of standardization at the binary level. Although the ISO/ANSI C++ Draft Working Paper attempts to codify which programs will compile and what the semantic effects of running them will be, it makes no attempt to standardize the binary runtime model of C++. The first time this problem will become evident is when a client tries to link against the FastString DLL's import library from a C++ developement environment other than the one used to build the FastString DLL.

结构填充由不同的编译器完成.即使您使用相同的编译器,结构的包装对齐方式也可能因 pragma pack 您正在使用.

Struct padding is done differently by different compilers. Even if you use the same compiler, the packing alignment for structs can be different based on what pragma pack you're using.

不仅是如果你写两个成员完全相同的结构,唯一的区别是它们声明的顺序不同,那么大小每个结构体可以(并且经常是)不同的.

Not only that if you write two structs whose members are exactly same, the only difference is that the order in which they're declared is different, then the size of each struct can be (and often is) different.

例如,看这个,

struct A
{
   char c;
   char d;
   int i;
};

struct B
{
   char c;
   int i;
   char d;
};

int main() {
        cout << sizeof(A) << endl;
        cout << sizeof(B) << endl;
}

gcc-4.3.4 编译它,你会得到这个输出:

Compile it with gcc-4.3.4, and you get this output:

8
12

也就是说,即使两个结构具有相同的成员,大小也不同!

That is, sizes are different even though both structs have the same members!

最重要的是,标准没有讨论应该如何进行填充,因此编译器可以自由做出任何决定,您不能假设所有编译器都做出相同的决定.

The bottom line is that the standard doesn't talk about how padding should be done, and so the compilers are free to make any decision and you cannot assume all compilers make the same decision.

这篇关于C++中的结构填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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