与 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
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/