c++ - 访问 union 中相同类型的非事件成员

标签 c++ undefined-behavior unions

我有这样的事情:

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 ]

你的 structs 共享一个共同的初始序列:

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/

相关文章:

c++ - 如何比较 char 或 string 变量是否等于某个字符串?

c++ - std::futures 和异常

c++ - 在 Type::var 的情况下,范围解析运算符返回什么?

c++ - 安全地将 void* 转换为 int

c++ - 在 const 对象上间接调用非常量函数

c++ - SEM_FAILCRITICALERRORS 会阻止什么?

c - "return i++, i, i++;"在 C 中是未定义的行为吗?

c++ - 如何访问 union 的内部成员?

c - 在标记的联盟上 dispatch

c - 当 union 位于 c 结构体内部时,sizeof() 将返回什么?