简体   繁体   English

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

[英]Does returning a reference extend its lifetime too?

AFAIK, in the following code the lifetime of the reference ro1 is extended till the end of the scope (function g() ): 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
}

How about returning this reference? 如何返回此引用? Will the object still live in g1() , or will it be destructed upon the exit from h() ? 对象是否仍然存在于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?
}

How about returning this reference? 如何返回此引用? Will the object still live in g1() 对象是否仍然存在于g1()

No. Lifetime extension is something that happens only one time. 不可以。终身延长只发生一次。 The temporary returned from f() is bound to the reference ro1 and its lifetime is extended for the lifetime of that reference. f()返回的临时值绑定到引用ro1并且其生命周期在该引用的生存ro1延长。 ro1 's lifetime ends at the end of h() , so any use of ro2 in g1() is a dangling reference. ro1的生命周期在h()结束时结束,因此在g1()使用ro2是一个悬空引用。

In order for this to work, you need to deal with values: 为了使其工作,您需要处理值:

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

Note that RVO still applies here. 请注意,RVO仍适用于此处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM