|
Boost : |
Subject: Re: [boost] Move semantics for std::string?
From: Robert Dailey (rcdailey_at_[hidden])
Date: 2012-02-17 10:57:02
On Fri, Feb 17, 2012 at 1:11 AM, Roman Perepelitsa <
roman.perepelitsa_at_[hidden]> wrote:
> 2012/2/17 Jeffrey Lee Hellrung, Jr. <jeffrey.hellrung_at_[hidden]>
> >
> > std::string foo()
> > {
> > std::string result;
> > /*...*/
> > // would like to "return x;", but instead...
> > result.swap(x);
> > return result;
> > /*...*/
> > // would like to "return y;", but instead...
> > result.swap(y);
> > return result;
> > }
>
>
> Simplified RVO rules: If all return statements in a function refer to the
> same local variable OR if a function returns an ravlue in all cases, the
> copy can (and in practice will) be elided.
>
> // RVO-enabled: always returns the same local variable.
> string foo() {
> string res;
> if (flag) {
> res = "hello";
> return res;
> } else {
> res = "bye";
> return res;
> }
> }
>
> // RVO-enabled: always returns a temporary.
> string foo() {
> if (flag)
> return "hello";
> else
> return "bye";
> }
>
> It's a good practice to make all functions you write RVO-enabled.
So all of these functions are functionally equivalent to simply
constructing a std::string object in the calling scope?
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk