c++ - C++ 中的结构填充

标签 c++ struct

如果我在 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/

相关文章:

C++ : Array of struct as function parameter

c++ - 如何将共享库链接到 linux 中的其他共享库?

c++ - 如何在 C++ 中处理多个 opencv 版本

c++ - C++ 中的“new”运算符和 typedef 数组

c - 为什么我会收到有关链表内字符数组的错误?

具有未导出字段的 Golang 结构文字语法

c++ - 如何在不更改原始数组的情况下对指向结构的指针数组进行排序?

c++ - 使用位运算符理解枚举成员的初始化

c++ - 分配的结构包含 vector 的内存泄漏

c++ - 使用 find_if 和 isalnum 在字符串中查找字母数字字符