AdlerSam Wrote:
> On 22 Feb., 10:07, Paul Brettschneider
> <paul.brettschnei...@yahoo.fr> wrote:
> > AdlerSam wrote:
> > > Hi,
> >
> > > I wonder why the following two lines produce a
> warning:
> >
> > > class X {};
> > > const X &f() {return X();}
> >
> > > $ g++ -c ref.cpp
> > > ref.cpp: In function ‘const X& f()’:
> > > ref.cpp:2: warning: returning reference to temporary
> >
> > > As far as I understand, a const reference _extends_ the
> lifetime of a
> > > temporary until the very last reference instance that refers to
> the
> > > temporary goes out of scope. Thus, where is the problem that
> justyfies
> > > the warning?
> >
> > This assumption is - of course - nonsense. If you want to manage
> lifetime of
> > objects, you usually use smart pointers or containers.
> >
> > Hope that helps.
>
> Hm - Then where do I have mistaken Herb Sutters GotW #88
>
>
http://herbsutter.com/2008/01/01/got...ost-important-
const/
>
> To quote the important part:
>
> > Normally, a temporary object lasts only until the end of the full
> expression in which it appears. However, C++
> > deliberately specifies that binding a temporary object to a
> reference to const on the stack lengthens the lifetime of
> > the temporary to the lifetime of the reference itself, and thus
> avoids what would otherwise be a common dangling
> > reference error. In the example above, the temporary returned
> by f() lives until the closing curly brace. (Note this
> > only applies to stack-based references. It doesn’t work for
> references that are members of objects.)
>
You go wrong when you assume this lifetime extension is transitive.
The lifetime of a temporary is indeed extended, but only to the lifetime of
the *initial* reference it is bound to.
If you use that reference to initialise a second reference, then the
lifetime of the temporary is not further extended.
In your initial example, the temporary is bound to the reference being
returned, so the lifetime of the temporary is extended to the lifetime of
the return value.
As this creates a great risk of getting a dangling reference (for example,
when you have the code "const X& x = f();"), most compilers will warn you
when you try to return a reference to something that won't live long enough
to be useful in the caller.
Bart v Ingen Schenau