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/