我有这样的事情:
union DataXYZ
{
struct complex_t
{
float real, imag;
} complex;
struct vector_t
{
float magnitude, phase;
} vector;
};
我有一些这些 vector ,作为通用工作空间内存,我在语义上下文之后相应地使用这些字段。
我知道当最后一个事件成员是另一个字段(和类型?)时,读取 union 中的字段是未定义的行为。当类型和布局完全匹配时,这是否重要?
我一直在评论一些其他类似的问题,要求提供保证行为的引用资料,但什么都没有出现 - 因此提出了这个问题。
最佳答案
是的您可以在这个特殊情况中读取其他成员。
这就是 C++11/14 标准所说的:
9.5 - Unions
In a union, at most one of the non-static data members can be active at any time, that is, the value of at most one of the non-static data members can be stored in a union at any time.
但是该部分之后的注释使您的特定实例合法,因为作出了一项特殊保证为了简化 union 的使用:
[ Note: If a standard-layout union contains several standard-layout structs that share a common initial sequence (9.2), and if an object of this standard-layout union type contains one of the standard-layout structs, it is permitted to inspect the common initial sequence of any of standard-layout struct members; see 9.2. —end note ]
你的 struct
s 共享一个共同的初始序列:
9.2.16 - Class members
The common initial sequence of two standard-layout struct (Clause 9) types is the longest sequence of non- static data members and bit-fields in declaration order, starting with the first such entity in each of the structs, such that corresponding entities have layout-compatible types and either neither entity is a bit-field or both are bit-fields with the same width.
关于c++ - 访问 union 中相同类型的非事件成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34677343/