关于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/