据我所知,在下面的代码中,引用
这个引用会如何返回?对象是否仍然存在于
ro1
的生命周期被延长到作用域结束(函数g()
):class Some {
// Implementation here
};
Some f() {
return Some(/* constructor parameters here*/);
}
void g() {
Some&& ro1 = f();
// ro1 lives till the end of this function
}
这个引用会如何返回?对象是否仍然存在于
g1()
中,还是在从 h()
退出时被销毁?Some&& h() {
Some&& ro1 = f();
// Code skipped here
return std::forward<Some>(ro1);
}
void g1() {
Some&& ro2 = h();
// Is ro2 still refering to a valid object?
}
std::forward<T>
,那么可以期望进行移动构造。但在你的第二个片段中,由于它是一个std::forward<T&&>
,因此它避免了任何构造并留下了悬空引用。 - TheWaterProgrammerg
返回本地临时变量时,它将被销毁,你会得到一个悬空引用。此外,我认为引用扩展仅适用于 const 引用而不是右值引用 - 我错过了什么吗?在 C++1z 中是否有所改变? - Richard Critten