Boost logo

Boost :

Subject: Re: [boost] Move semantics for std::string?
From: Roman Perepelitsa (roman.perepelitsa_at_[hidden])
Date: 2012-02-17 02:11:17

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";
    return "bye";

It's a good practice to make all functions you write RVO-enabled.

Roman Perepelitsa.

Boost list run by bdawes at, gregod at, cpdaniel at, john at