Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()):

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()?

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?
}
like image 206
Serge Rogatch Avatar asked Mar 13 '26 06:03

Serge Rogatch


1 Answers

How about returning this reference? Will the object still live in 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. ro1's lifetime ends at the end of h(), so any use of ro2 in g1() is a dangling reference.

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.

like image 59
Barry Avatar answered Mar 15 '26 18:03

Barry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!