title: STL swap on return?
body: <p>sorry for such a long question but I try to be as clear as possible. This somehow follows my previous question about <a href="https://stackoverflow.com/questions/4714494/which-string-classes-to-use-in-c">strings in C++</a>. I'm trying to figure out how I could return std::string from a function without redundant memory allocations, <em>without relying on NRVO</em>. The reasons why I don't want to rely on NRVO are:</p>
  
  <ul>
  <li>it is not supported by the compiler we currently use</li>
  <li>even when it is supported it might not always be enabled in Debug mode</li>
  <li>it might fail in some cases (<a href="http://en.wikipedia.org/wiki/Return_value_optimization#Compiler_support" rel="nofollow noreferrer">example</a>)</li>
  </ul>
  
  <p>Please note that I need a C++03 compatible solution (no C++0x rvalue references thus, unfortunately...)</p>
  
  <p>The simplest way do this is pass-by-reference and do std::swap, like this</p>
  
  <pre><code>void test(std::string&amp; res)
  {
      std::string s;
      //...
      res.swap(s);
  }
  </code></pre>
  
  <p>But it is more natural and often more convenient to return by value than pass by reference, so what I want to achieve is this:</p>
  
  <pre><code>std::string test()
  {
      std::string s;
      //...
      return SOMETHING(s);
  }
  </code></pre>
  
  <p>Ideally it would just do a <code>swap</code> with the "return value", but I don't see how to do this in C++. There is auto_ptr already which does move instead of copy, and I could actually use <code>auto_ptr&lt;string&gt;</code>, but I'd like to avoid dynamically allocating the string object itself.</p>
  
  <p>My idea is to somehow "tag" a string object that it is being returned from a function to permit <em>moving</em> its data when a copy constructor is called on return. So I ended up with this code, which does exactly what I want:</p>
  
  <pre><code>struct Str
  {
      struct Moveable
      {
          Str &amp; ref;
          explicit Moveable(Str &amp; other): ref(other) {}
      };
  
      Str() {}
      Str(const std::string&amp; other) : data(other) {} // copy
      Str(Moveable&amp; other) { data.swap(other.ref.data); } // move
  
      Moveable Move()
      {
          return Moveable(*this);
      }
  
      std::string data;
  };
  
  Str test()
  {
      Str s;
      //...
      return s.Move(); // no allocation, even without NRVO
  }
  </code></pre>
  
  <p>So... Does all this make sense, or there are some serious issues that I'm missing? (I'm not sure if there is no lifetime issue for example). Maybe you have already seen such idea in a library (book, article...), and could give me a reference to it?</p>
  
  <p>EDIT: As @rstevens noticed, this code is MSVC-specific and won't compile under g++ which does not like the non-const temporary. This <em>is</em> an issue, but let's just assume this implementation is MSVC-specific.</p>