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

Ser*_*tch 3 c++ reference lifetime rvalue-reference c++17

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
}
Run Code Online (Sandbox Code Playgroud)

如何返回此引用?物体是否仍然存在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?
}
Run Code Online (Sandbox Code Playgroud)

Bar*_*rry 5

如何返回此引用?对象是否仍然存在g1()

不可以.终身延长只发生一次.返回的临时f()值绑定到引用ro1,其生命周期在该引用的生命周期内延长.ro1生命的终结在结尾h(),所以任何使用ro2in g1()都是悬挂的参考.

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

Some h() {
  Some ro1 = f();
  // Code skipped here
  return ro1;
}
Run Code Online (Sandbox Code Playgroud)

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