c++ - 结构前缀的布局

标签 c++ c struct casting

C/C++ 语言不会对内存中的结构成员重新排序,也不会在第一个成员之前插入填充。但是如果我有 2 个以相同成员开头的结构,如果我只访问公共(public)成员,我可以在它们之间转换吗?换句话说,struct layout 是贪心的吗?我的具体案例在 VIDEOINFOHEADER 之间类型转换和 VIDEOINFOHEADER2

最佳答案

C++ 标准包含以下声明,但仅适用于 union (9.2 [class.member] 第 19 段):

If a standard-layout union contains two or more standard-layout structs that share a common initial sequence, and if the standard-layout union object currently contains one of these standard-layout structs, it is permitted to inspect the common initial part of any of them. Two standard-layout structs share a common initial sequence if corresponding members have layout-compatible types and either neither member is a bit-field or both are bit-fields with the same width for a sequence of one or more initial members.

对于 C 或 C++ 标准中部分定义的结构,我没有看到任何其他保证。不过,这并不意味着它不存在,只是我没有通过快速浏览几个相关部分找到它。

关于c++ - 结构前缀的布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20788934/

相关文章:

c++ - 抽象类对象和纯虚析构函数

c - 将函数指针指向函数的位置

c - C 中使用结构数组指针进行循环控制

c++ - 如何在窗口外绘制图形(OpenGL glfw)

c++ - 在 C++ 中使用 rpcgen

c++ - 如何使用 Intel PIN 获取内存操作值?

c - 试图获取操作时间和接收时间 0 秒

c - 如何让 getservbyname() C 库调用在 Mac 上正常工作?

c++ - C(++) 结构力额外填充

c++ - 有一个带有方法的结构总是邪恶的吗?