c++ - 是否允许类型相同但大小不同的双关数组?

标签 c++ arrays language-lawyer type-punning

相同类型但大小不同的类型双关数组是否仍然违反严格别名?

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 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.

即可以说,我们有一个指针指向第一个元素(不仅仅是代表地址)。它属于该元素的类型。因此访问 ref[0] 应该被定义。

按照这个逻辑,这样写也是可以的

auto& ref = reinterpret_cast<unsigned(&)[200]>(arr);
std::cout << ref[0];

关于c++ - 是否允许类型相同但大小不同的双关数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36051008/

相关文章:

c++ - 可以默认初始化具有已删除默认构造函数的类类型吗?

c++ - 引用类成员琐碎

c++ - C 运行时 CRT 与 C++ 运行时 - 堆内存管理模型

c++ - 模板化(或以某种方式自动)方法的返回值

c - 快速排序数组随机数生成器没有打印任何错误

Python "Hangman"代码

c++ - 我是否必须手动删除 QSet 的每个(指针)元素?

c++ - 使用 native /C++ 代码在 VS2010 中创建简单 COM 对象的最简单方法是什么?

java - 普通数组的列表操作

c++ - 函数 try catch 语法和 main