相同类型但大小不同的类型双关数组是否仍然违反严格别名?
int arr[4];
int(&ref)[2] = reinterpret_cast<int(&)[2]>(arr);
arr[0] = 0; //write to original
ref[0]; //read from pun
最佳答案
我们可以争论如下; [expr.reinterpret.cast]/11 :
A glvalue expression of type
T1
can be cast to the type “reference toT2
” if an expression of type “pointer toT1
” can be explicitly converted to the type “pointer toT2
” using areinterpret_cast
. The result refers to the same object as the source glvalue, but with the specified type.
An lvalue or rvalue of type “array of
N T
” […] can be converted to a prvalue of type “pointer toT
”. The result is a pointer to the first element of the array.
即可以说,我们有一个指针指向第一个元素(不仅仅是代表地址)。它属于该元素的类型。因此访问 ref[0]
应该被定义。
按照这个逻辑,这样写也是可以的
auto& ref = reinterpret_cast<unsigned(&)[200]>(arr);
std::cout << ref[0];
关于c++ - 是否允许类型相同但大小不同的双关数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36051008/