3
AFAIK,在下面的代码的参考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?
}
您的第二个片段无延长寿命。 – Jarod42
**如果**它是'std :: forward',那么可以预期移动结构。但是在你的第二段代码中,**因为它是'std :: forward ',因此它避免了任何构造并且留下了悬挂的引用 –
当'g'返回本地临时被销毁并且你留下了一个悬而未决的参考。此外,我认为参考扩展只适用于const ref而非rvalue参考 - 我错过了什么,在C++ 1z中做了这种改变? –