Is type punning arrays of same type but different size allowed?

给你一囗甜甜゛ 提交于 2020-01-02 08:33:16

问题


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 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];


来源:https://stackoverflow.com/questions/36051008/is-type-punning-arrays-of-same-type-but-different-size-allowed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!