使用整数指针将左值转换为右值

Lvalue to rvalue conversion with integer pointer

本文关键字:转换 整数 指针      更新时间:2023-10-16

如果我正确读取隐式转换:

左值到右值的转换

任何非函数、非数组类型 T 的 glvalue 都可以隐式转换为相同类型的 prvalue。[..]

除非在未计算的上下文中遇到(在 sizeof、typeid、noexexcept 或 decltype 的操作数中(,否则此转换使用原始 glvalue 作为构造函数参数有效地复制构造类型 T 的临时对象,并且该临时对象作为 prvalue 返回。

那为什么这不起作用呢?

int* iptr = nullptr;
int*&& irr = iptr; // Cannot bind lvalue to rvalue reference

类型 int* 应该通过临时隐式转换为相同类型的 prvalue,从而绑定到右值引用而不会出现问题。

标准明确指出这是格式不正确的; 不会(不应该(考虑左值到右值的转换。

来自 [dcl.init.ref]/5.4.4:

如果引用是

右值引用,则初始值设定项表达式不应是左值。

[ 示例:

double d2 = 1.0;
double&& rrd2 = d2;                 // error: initializer is lvalue of related type