c++ - 为什么右值引用整数合法

标签 c++ c++11 reference

关于C++ 11,这可能是一个愚蠢的问题,但这确实让我感到困扰。
据我了解,右值引用也是一个引用,这意味着它将引用指向到某个变量,就像引用一样。
例如,

const int &ref = 1;
引用ref指向无法修改的纯右值1,这就是为什么编译器迫使我们使用const的原因。
另一个例子,
Bar&& GetBar()
{
    Bar b;
    return std::move(b);
}
此函数将返回一个悬空的引用,因为b写入后return被破坏了。
一言以蔽之,右值引用就是一个引用。
现在我很困惑。请检查以下代码:
int &&rref = 1;
如果右值引用也是一个引用,那么现在rref 指向纯右值1,根据我的理解,该值不应该编译,因为如果它是可编译的,那么我执行rref = 2怎么办?这是否意味着纯右值已更改:1变为2
但是gcc告诉我它是可编译的...
为什么?为什么我们不需要const int &&rref = 1

最佳答案

cppreference的报价

The lifetime of a temporary object may be extended by binding to a const lvalue reference or to an rvalue reference (since C++11), see reference initialization for details.


带有指向其他详细信息的链接here

Whenever a reference is bound to a temporary or to a subobject thereof, the lifetime of the temporary is extended to match the lifetime of the reference, with the following exceptions:


然后继续列出一些异常(exception),例如

a temporary bound to a return value of a function in a return statement is not extended: it is destroyed immediately at the end of the return expression. Such function always returns a dangling reference.


a temporary bound to a reference member in a constructor initializer list persists only until the constructor exits, not as long as the object exists. (note: such initialization is ill-formed as of DR 1696). (until C++14)


a temporary bound to a reference parameter in a function call exists until the end of the full expression containing that function call: if the function returns a reference, which outlives the full expression, it becomes a dangling reference.


a temporary bound to a reference in the initializer used in a new-expression exists until the end of the full expression containing that new-expression, not as long as the initialized object. If the initialized object outlives the full expression, its reference member becomes a dangling reference. (since C++11)


a temporary bound to a reference in a reference element of an aggregate initialized using direct-initialization syntax (parentheses) as opposed to list-initialization syntax (braces) exists until the end of the full expression containing the initializer. (since C++20)


所以推理
const int &ref = 1;
有效,因为我们使用的const不正确。编译器实际上是在扩展临时对象的生存期,以匹配引用的生存期。因此,使用右值引用执行相同的操作同样有效。
另一方面
int &ref = 1;
因为1不是左值,所以没有任何意义。这就是为什么我们需要const或右值引用的原因。

关于c++ - 为什么右值引用整数合法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64084983/

相关文章:

C++:如何让不同的类函数操作我的类成员变量

c++ - 为什么没有 std::future::try_wait()?

c++ - 如何提取/扩展可变模板参数

Java - 具有相同引用的对象池

Java MVP - 不持有 Presenter 对象的引用?

php - 有没有办法访问给定对象的所有引用?

c++ - 函数名称修改。 _cdecl约定

c++ - 在基于对话的项目与 SDI 项目之间进行选择

c++ - 用于模板函数特化的 Enable_if

c++ - 为什么访问嵌套类型会影响 C++ 中的成员解析?