访问联合中的同类型非活动成员

Accessing same-type inactive member in unions

我有这样的东西:

union DataXYZ
{
    struct complex_t
    {
        float real, imag;
    } complex;

    struct vector_t
    {
        float magnitude, phase;
    } vector;
};

我有一些这些向量,作为通用工作区内存,我在语义上下文之后相应地使用这些字段。

我知道当最后一个活动成员是另一个字段(和类型?)时,读取联合中的字段是未定义的行为。当类型和布局完全匹配时,这有关系吗?

我一直在评论其他一些类似的问题,要求提供保证行为的参考资料,但还没有任何结果 - 因此这个问题。

你可以在这个特殊情况下阅读其他成员

这是 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.

但是紧接在该部分之后的注释使您的特定实例合法,因为做出了一项特殊保证以简化联合的使用:

[ 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 共享 一个共同的初始序列:

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.