返回引用是否也会延长其生存期?
Does returning a reference extend its lifetime too?
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 在此处仍然适用。
相关文章:
- 指针引用的生存期(以 C++为单位)
- 对临时对象的Const引用不会延长其生存期
- 返回引用是否也会延长其生存期?
- 超出返回引用的单一实例生存期
- 右值引用的生存期
- 仅允许从对较长生存期值的引用进行隐式构造
- 有没有办法在对象上保留弱引用并控制其生存期
- 为什么常量引用不能延长通过函数传递的临时对象的生存期?
- 为什么 C++ 从推断的返回类型中去除引用限定符,为什么生存期延长不起作用?
- 成员重新值引用和对象生存期
- 对临时与指向临时及其生存期的指针的引用
- 延长具有右值引用的临时的生存期
- 传递给存储常量引用的成员的临时对象的生存期
- 临时绑定到引用参数的默认参数的生存期是多少
- 如何延长从访问器返回的右值引用的生存期
- 三元运算符和通过引用const延长临时对象的生存期
- 绑定到函数参数的引用是否会延长该临时参数的生存期
- 引用/intilializer_list的生存期
- 未扩展常量引用变量的生存期
- 引用相对于其目标的生存期