是同型不同尺寸的双关类型的数组允许的? [英] Is type punning arrays of same type but different size allowed?

查看:137
本文介绍了是同型不同尺寸的双关类型的数组允许的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的类型是相同类型的,但具有不同的尺寸仍然严格走样的违规行为?夯实阵列

  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,但与指定的类型。


[conv.array]


  

这是左值或键入 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 to T2" if an expression of type "pointer to T1" can be explicitly converted to the type "pointer to T2" using a reinterpret_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 to T". 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆