考虑以下函数。我想要 C++17 的答案。
MyClass&& func() {
return MyClass{};
}
int main() {
MyClass&& myRef = func();
}
问题:
- 表达式
func()
是一个 xvalue 吗?为什么? - 为什么
myRef
是悬空引用?或者,更具体地说,为什么func()
返回悬空引用?返回右值引用不会导致临时物化,并延长临时对象的生命周期吗?
最佳答案
func()
是一个 xvalue,因为该语言的规则之一是,如果一个函数被声明为具有对对象的右值引用的返回类型,则由调用该函数组成的表达式是一个 xvalue 。 (C++17 expr.call/11).
Temporary materialization任何时候引用绑定(bind)到纯右值时都会发生。
函数的结果是myRef
,它由纯右值func()
初始化。然而,如果我们查阅 class.temporary/6 中的生命周期延长规则,它有:
The lifetime of a temporary bound to the returned value in a function return statement is not extended; the temporary is destroyed at the end of the full-expression in the return statement.
因此 func()
实现的临时对象在 return
语句完成时被销毁,没有扩展。
关于c++ - 返回右值引用和临时物化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62296253/