是同型不同尺寸的双关类型的数组允许的? [英] Is type punning arrays of same type but different size allowed?
问题描述
的类型是相同类型的,但具有不同的尺寸仍然严格走样的违规行为?夯实阵列
INT ARR [4];
INT(安培;参考文献)[2] = reinter pret_cast&下; INT(安培)[2]≥(改编);改编[0] = 0; //写原创
参考文献[0]; //从读取的双关语
我们可以讨论如下: [expr.reinter pret.cast] / 11
类型的glvalue前pression
T1
可强制转换为类型参考
到T2
如果类型的前pression指针T1
可以明确地
转换的类型指针T2
使用reinter pret_cast
。
结果指的是同一个对象作为源glvalue,但与指定的类型。
块引用>
这是左值或键入
NT·
数组的右值[...]可转换为
类型prvalue指针T
。 的结果是一个指针
数组的第一个元素。
块引用>即。可以说,我们有点的指针的到(不只是单纯重presents的地址)的第一个元素。它是该元素的类型。因此访问
REF [0]
应该定义。根据这个逻辑,这也是精写
汽车及放大器; REF = reinter pret_cast<无符号(安培)[200]>(ARR);
性病::法院LT&;<参考文献[0];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
解决方案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.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];
这篇关于是同型不同尺寸的双关类型的数组允许的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!