返回引用是否也会延长其生存期?

Does returning a reference extend its lifetime too?

本文关键字:生存期 引用 是否 返回      更新时间:2023-10-16

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?
}

返回此引用怎么样?该对象是否仍存在于g1()

不。寿命延长是只发生一次的事情。从f()返回的临时将绑定到引用ro1,并且其生存期在该引用的生存期内延长。ro1的生命周期在h()结束时结束,所以任何在g1()中使用ro2都是悬而未决的参考。

为了使其正常工作,您需要处理值:

Some h() {
Some ro1 = f();
// Code skipped here
return ro1;
}

请注意,RVO 在此处仍然适用。