c++ - 数组元素算作一个共同的初始序列吗?

标签 c++ arrays language-lawyer unions

my previous question 有点相关:

数组的元素算作一个共同的初始序列吗?

struct arr4 { int arr[4]; };
struct arr2 { int arr[2]; };

union U
{
    arr4 _arr4;
    arr2 _arr2;
};

U u;
u._arr4.arr[0] = 0; //write to active
u._arr2.arr[0]; //read from inactive

根据this cppreference page :

In a standard-layout union with an active member of non-union class type T1, it is permitted to read a non-static data member m of another union member of non-union class type T2 provided m is part of the common initial sequence of T1 and T2....

这是合法的,还是非法的类型双关语?

最佳答案

C++11 说 (9.2):

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.

关于不同大小的数组是否构成有效的公共(public)初始序列,3.9说:

If two types T1 and T2 are the same type, then T1 and T2 are layout-compatible types

这些数组不是同一类型,所以这不适用。数组没有特殊的进一步异常(exception),因此数组可能不兼容布局并且不形成共同的初始序列。

不过,在实践中,我知道有一个编译器 (GCC):

  • 忽略“共同初始序列”规则,并且
  • 无论如何都允许类型双关语,但仅当访问是“通过 union 类型”(如您的示例中)时,在这种情况下,间接遵守“共同初始序列”规则(因为“共同初始序列”意味着共同编译器支持的架构的初始布局)。

我怀疑许多其他编译器采用了类似的方法。在您的示例中,您通过 union 对象键入双关语,此类编译器将为您提供预期的结果 - 从非事件成员读取应该为您提供通过非事件成员写入的值。

关于c++ - 数组元素算作一个共同的初始序列吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36051084/

相关文章:

c++ - 使用模板返回节点指针

C++ : why is my average returning as an int and not a double?

c++ - 在 C++ 插件中卸载静态实例变量?

java - 最终 2D 数组数据在不使用 Java 隐式更改其值的情况下进行更改

C++11 对 lambda 返回类型的限制

c++ - 比较悬挂指针是否合法?

c++ - 将 memset bool 设置为 0 是否安全?

c++ - 获取所有函数重载的参数类型

javascript - 使用高整数数组索引有什么负面影响吗?

javascript - 如何将javascript数组转换为函数