通过指针恢复对数组的引用.UB与否?
Restore reference to array by pointer. UB or not?
>我正在尝试找到一种通过指针恢复对数组的引用的方法。
查看代码:
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
(。
相关文章:
- 将对象数组的引用传递给函数
- 什么时候在C++中返回常量引用是个好主意
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 何时在引用或唯一指针上使用移动语义
- 如何在c++中使用引用实现类似python的行为
- 编译C++时未定义的引用
- Ctypes wstring通过引用传递
- c++r值引用应用于函数指针
- 理解c++中的引用
- C++取消引用指针.为什么会发生变化
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 强制转换为引用类型
- 引用一个已擦除类型(void*)的指针
- 通过指针恢复对数组的引用.UB与否?
- C++ - 使用常量引用来延长临时成员,确定还是 UB?
- 为什么在使用 auto&&it=--vec.end(),是 UB 时自动推导左值引用?
- 中毒的无效引用和短路表达评估错误或UB
- rvalue引用lVALUE参考-UB