Topic: Lifetime of reference


Author: clamage@Eng.Sun.COM (Steve Clamage)
Date: 8 Feb 1995 17:20:13 GMT
Raw View
In article 26174@nlm.nih.gov, rubenst%occs.nlm.nih.gov (Mike Rubenstein Phoenix Contract) writes:
>What is the lifetime of a reference returned from a function?
>
> ...  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.

The wording you quote applies to compiler-generated temporaries. If the
reference returned from a function is to some object which is not a compiler-
generated temp, the object's lifetime is independent of the lifetime of the
reference to which it is bound. (It is possible to have a dangling reference
in any case, quite apart from things returned from functions.)

Since a reference must be bound to an object at the instant of its creation,
the reference cannot live longer than the block where it is declared.
(Unless it is at file scope, in which case it and the object live until the
end of the program.)
---
Steve Clamage, stephen.clamage@eng.sun.com






Author: rubenst%occs.nlm.nih.gov (Mike Rubenstein Phoenix Contract)
Date: Tue, 7 Feb 95 23:28:53 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