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

Do array elements count as a common initial sequence?

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.

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

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

这些数组不是同一类型,因此这不适用。数组没有特殊的进一步例外,因此数组可能与布局不兼容并且不形成共同的初始序列。

不过,实际上,我知道一个编译器 (GCC):

  • 忽略"common initial sequence"规则,并且
  • 无论如何都允许类型双关,但只有当访问是 "via the union type" 时(如您的示例所示),在这种情况下间接遵守 "common initial sequence" 规则(因为 "common initial sequence" 意味着编译器支持的体系结构上的通用初始布局)。

我怀疑许多其他编译器也采用类似的方法。在您的示例中,您通过联合对象输入双关语,这样的编译器将为您提供预期的结果 - 从非活动成员读取应该为您提供通过非活动成员写入的值。