Boost logo

Boost :

From: David Abrahams (dave_at_[hidden])
Date: 2002-09-04 14:53:41


From: "Hillel Y. Sims" <hsims_at_[hidden]>

>
> 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?

Typically the RVO is implemented by allocating space for the result in the
caller. The caller would have to allocate space for T whenever the return
type was T&, if this were to be true, and would have to know whether a
temporary was bound, and would have to generate a destructor...a terrible
pessimization.

-----------------------------------------------------------
           David Abrahams * Boost Consulting
dave_at_[hidden] * http://www.boost-consulting.com


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