Topic: Lifetime of returned reference


Author: rick@triode.apana.org.au (Richard Welykochy)
Date: 26 Jan 1995 16:37:30 GMT
Raw View
Mike Rubenstein Phoenix Contract (rubenst%occs.nlm.nih.gov) wrote:
: What is the lifetime of a reference returned from a function?
[skip]
:  const B& foo()
:  {
:    return B(0);
:  }

The reference lasts forever.  Sadly, the B(0) temporary does not.
As a matter of fact, it is destroyed by foo() is exited.
You've uncovered one of the many ways the unweary programmer
can wind up with a notorious "dangling reference" in C++.
Good compilers issue a warning in this specific case.
Solution: DON'T DO IT! (Or switch languages).




Author: rubenst%occs.nlm.nih.gov (Mike Rubenstein Phoenix Contract)
Date: Sun, 22 Jan 95 22:00:34 GMT
Raw View
What is the lifetime of a reference returned from a function?

Consider

 class B {
   public:
     B(int);
 };

 const B& foo()
 {
   return B(0);
 }

 bar()
 {
   B b = foo();
 }

When is the temporary created in foo destroyed?  According to the draft
"the lifetime of a temporary object bound to a reference ... is the
lifetime of the reference itself."  If the lifetime of the returned reference
extends beyond the execution of the function, then the temporary must be
destroyed after the function returns.  I find it very hard to believe that
this is intended, but I don't find the idea that the lifetime of the reference
ends with the function very appealing either.

I believe the above code should be illegal or, at least, result in
undefined behavior, but I can't find anything in the draft that disallows it.

What am I missing?

--
Mike Rubenstein