Boost logo

Boost Users :

From: Ben Hutchings (ben.hutchings_at_[hidden])
Date: 2003-04-24 12:26:11


Duane Murphy <duanemurphy_at_[hidden]> wrote:
> --- At Thu, 24 Apr 2003 16:56:40 +0100, Ben Hutchings wrote:
> >dick.bridges_at_[hidden] wrote:
> >> I don't understand C++ well enough to grok a compiler's
interpretation of
> >> the code, but I seems like I'm creating an extra copy for the
return.
> ><snip>
> >
> >Logically the local variable is copied to the the caller, but since
the type
> >of the returned expression matches the return type the compiler is
allowed
> >to optimise away that copy, even though the return type has a
user-defined
> >copy constructor. In this case you always return a certain named
variable,
> >so the compiler can arrange to construct it in the memory location
where the
> >caller expects the returned value. This is called the
named-return-value
> >optimisation, or NRVO.
>
> I dont want to start any kind of war, and this is a bit off topic, but
I
> was investigating NVRO and found a few discussions with Scott Meyers
that
> indicated that naming is not relevant to the optimization. That this:
>
> shared_ptr<int> maybe_get_a_pointer()
> {
> return shared_ptr<int>();
> }
>
> is perfectly reasonable and can also be optimized.
>
> Is there more recent and complete discussion concerning this
> optimization? Is naming actually required?

I realise that the implementation is allowed to optimise out the copy
whether the return value is named or not. Actually doing so requires
quite different treatment of the two cases, so it's worth considering
them as separate optimisations.

For NRVO to be possible at some return statement, there must not be any
return statements reachable after the construction of the returned
object
that return any other object. The optimisation involves changing the
code generated for the definition of the object, rather than the code
for the return statement. So the implementation has to consider the
whole function when doing this.

Anonymous RVO is a very local optimisation, so it should require less
work to apply.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net