如果我在 C++ 中有一个 struct
,是否没有办法安全地将它读/写到跨平台/编译器兼容的文件中?
因为如果我理解正确的话,每个编译器都会根据目标平台进行不同的“填充”。
最佳答案
没有。这是不可能的。这是因为 C++ 在二进制级别缺乏标准化。
Don Box写道(引用自他的书 Essential COM,章节 COM 作为更好的 C++)
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 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
编译它,你会得到这个输出:
8
12
也就是说,即使两个结构具有相同的成员,大小也不同!
最重要的是,该标准并未讨论应如何进行填充,因此编译器可以自由做出任何决定,您不能假定所有编译器都做出相同的决定。
关于c++ - C++ 中的结构填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42684064/