From: Anthony Williams (anthwil_at_[hidden])
Date: 2002-09-05 05:04:35


 Hillel Y. Sims writes:
>
> "Anthony Williams" <anthwil_at_[hidden]> wrote in message
> news:15733.50724.159000.285126_at_gargle.gargle.HOWL...
> > David B. Held writes:
> > > // Requirements:
> > > // T must be default-constructible
> > > template <typename T>
> > > T const& safe_dereference(T* p)
> > > {
> > > return p ? *p : T();
> > > }
> > >
> >
> > I can see the point, but this is undefined behaviour --- you are returning
> a
> > reference to a temporary, which as gone out of scope.
> >
>
> Why is it ok to say
>
> int main()
> {
> const string& s = func();
> cout << s << endl;
> }
>
> when func is defined as
> string func() { return string("hello"); }
>
> but then not ok if func is
> const string& func() { return string("hello"); } ?
>
> Is it not possible for a compiler to bind the temporary directly to the
> const & in both cases?

No. The second case is _identical_ to

const string& func()
{
    string temp("hello");
    return temp;
}

Which, returns a reference to a local variable, and which I hope you agree is
therefore undefined behaviour. Anywhere you use

const X&someRef=some_expression_resulting_in_a_temporary_X;

to extend the life of a temporary, you can write

X someVar=some_expression_resulting_in_a_temporary_X;
const X& someRef=someVar;

and you cannot tell the difference, give or take some invocations of the copy
constructor, which are optional in both cases anyway.

Anthony