问题
Is type punning arrays of the same type but with a different size still a violation of strict aliasing?
int arr[4];
int(&ref)[2] = reinterpret_cast<int(&)[2]>(arr);
arr[0] = 0; //write to original
ref[0]; //read from pun
回答1:
We can argue as follows; [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.
[conv.array]:
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.
I.e. arguably, we have a pointer that points to (not just merely represents the address of) the first element. And it is of that element's type. Thus accessing ref[0]
should be defined.
By this logic, it is also fine to write
auto& ref = reinterpret_cast<unsigned(&)[200]>(arr);
std::cout << ref[0];
来源:https://stackoverflow.com/questions/36051008/is-type-punning-arrays-of-same-type-but-different-size-allowed