通过指针恢复对数组的引用.UB与否?

Restore reference to array by pointer. UB or not?

本文关键字:引用 UB 与否 数组 指针 恢复      更新时间:2023-10-16

>我正在尝试找到一种通过指针恢复对数组的引用的方法。

查看代码:

const int rows = 2;
const int cols = 3;
int arr[rows][cols] = { {1,2,3}, {4,5,6} }; // step0
int(&arr_ref)[rows][cols] = arr; // create a a reference from array - OK
int* some_ptr = &arr[0][0]; // step1. create pointer to array - OK
//int(&arr_ref2)[rows][cols] = *some_ptr; // step2 (failed). restore the array reference from the pointer. impossible.
int(&arr_ref3)[rows][cols] = reinterpret_cast<int(&)[rows][cols]>(*some_ptr); // step2. ok???
  • step0:我们有一些数组
  • 步骤 1:从数组创建简单指针
  • 步骤2:从指针恢复引用。如何正确操作?

如果我绝对确定数组的大小,使用reinterpret_cast是否会导致未定义的行为。

更努力。如果我们想得到一个不同大小和"形状"的数组,但它肯定在原始数组的边界内。下面的代码"合法"吗?

int arr2[6] = { 1,2,3,4,5,6 };
int* some_ptr2 = &arr2[0];
int(&arr2_ref)[2][2] = reinterpret_cast<int(&)[2][2]>(*some_ptr2); // ok???

UPD:如果数组包含具有继承、虚函数等的复杂对象,它会起作用吗?它会是一个可靠的解决方案吗?

你必须投射:

int(&arr_ref2)[rows][cols] = (int(&)[rows][cols])some_ptr;

当您声明指针int* some_ptr = &arr[0][0];时,您将声明指向数组中第一个 int 的指针:指向一个 int 的指针。因此,您必须将指针投射回数组。 并且不要引用指针(带*some_ptr(。