Boost logo

Boost :

From: Thomas Wenisch (twenisch_at_[hidden])
Date: 2002-09-04 16:34:31

Hi David, all

Since Hillel posted the output of Comeau, I am certain that Comeau is
correct and my analysis of the standard is wrong, as it has always been
that way in the past. GCC 3.1 also diagnoses code. However, now I am not
sure why (ie what part of the standard) tells me this is the case.

In the example David included below, I clearly see the temporary being
bound to two references. First, it is bound to the parameter, x_. Since
x_ is a const reference, the life of the temporary is extended to the life
of x_ (which doesn't change anything, since it would have lived to the end
of the full-expression "h = new hold(f())" anyway). However, in the
initialization of x, the life does not get extended again, since it is
being initialized from another reference, not from the temporary. Thus, x
is left as a dangling reference.

The short analysis is temporary lifetimes are only extended by the first
const reference that binds to them.

What I am missing is where there are two references in the original code
(or the shorter version Hillel posted). From the text of David's message,
it seems the first const reference is an unnamed temporary created by the
return statement. Is this correct? If thats the case, then everything
makes sense to me, and I see why the compilers are right and I am wrong.
If that is not the case, then I am utterly confused.

David's example follows:

On Wed, 4 Sep 2002, David Abrahams wrote:

> From: "Thomas Wenisch" <twenisch_at_[hidden]>
> Yes, but that reference is created within the function. There's another
> reference on the outside of the function. By your logic, the temporary
> would live forever in this code:
> int f();
> struct hold { hold(int const& x_) : x(x_) {} int const& x; }
> hold* h = new hold(f());
> But it doesn't work that way.

-Tom Wenisch

Boost list run by bdawes at, gregod at, cpdaniel at, john at