Boost logo

Boost :

From: Hillel Y. Sims (hsims_at_[hidden])
Date: 2002-09-04 12:44:30


"Thomas Wenisch" <twenisch_at_[hidden]> wrote in message
news:Pine.LNX.4.21L.0209041259270.805-100000_at_dalmore.ece.cmu.edu...
>
>
>
> This is incorrect. The code returns a *const* reference to the
> temporary. This extends the life of the temporary to the life of the
> reference.
>
> The relevant parts of the standard are 12.2 and 8.5.3. Its pretty hard to
> piece all the rules together (I think there was a thread on this here or
> in comp.lang.c++.moderatord recently), but, basically, 12.2 says that if a
> reference is bound to a temporary, the life of the temporary extends to
> the life of the reference. 8.5.3 says that only non-volatile const
> references may be bound to rvalues (exception: rvalues that can be
> converted to lvalues via some conversion sequence). So 12.2 specifies the
> lifetime, and 8.5.3 makes the return legal.
>

EDG's translator does not agree with you:

http://www.comeaucomputing.com/tryitout/
Comeau C/C++ 4.3.0.1 (Aug 20 2002 15:39:28) for ONLINE_EVALUATION
Copyright 1988-2002 Comeau Computing. All rights reserved.
MODE:strict errors C++

"864.c", line 3: warning: returning reference to local temporary
  const string& func() { return string("hello"); }

..but I too do not fully understand why this is different than "string
func() { return string("hello"); }", which is acceptable. I suspect it has
something to do with general C++ return by copy semantics whereby the
reference binding the temporary goes away and the caller only gets a copy of
that reference, which doesn't hold the binding; but on the other hand, the
compiler is generally allowed to optimize away that copy, in which case
shouldn't it be able to bind it directly to the reference in the caller's
code?

hys

--
Hillel Y. Sims
FactSet Research Systems
hsims AT factset.com

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk