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

时间:2017-08-12 19:09:48

标签: c++ reference c++17 rvalue-reference lifetime

AFAIK,在以下代码中,引用def foo(bar): def test(some_string): print(some_string) return 'Decorator test: '+bar(some_string) return test 的生命周期延长到范围结束(函数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()

1 个答案:

答案 0 :(得分:5)

  

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

没有。终身扩展只发生一次。从f()返回的临时值绑定到引用ro1,其生命周期在该引用的生命周期内延长。 ro1的生命周期在h()结尾处结束,因此在ro2中使用g1()是一个悬空参考。

为了实现这一点,您需要处理值:

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

请注意,RVO仍适用于此处。

相关问题