title: Why does std::move prevent RVO (return value optimization)?
body: <p>In many cases when returning a local from a function, RVO (return value optimization) kicks in. However, I thought that explicitly using <code>std::move</code> would at least enforce moving when RVO does not happen, but that RVO is still applied when possible. However, it seems that this is not the case.</p>
  <pre><code>#include &quot;iostream&quot;
  
  class HeavyWeight
  {
  public:
      HeavyWeight()
      {
          std::cout &lt;&lt; &quot;ctor&quot; &lt;&lt; std::endl;
      }
  
      HeavyWeight(const HeavyWeight&amp; other)
      {
          std::cout &lt;&lt; &quot;copy&quot; &lt;&lt; std::endl;
      }
  
      HeavyWeight(HeavyWeight&amp;&amp; other)
      {
          std::cout &lt;&lt; &quot;move&quot; &lt;&lt; std::endl;
      }
  };
  
  HeavyWeight MakeHeavy()
  {
      HeavyWeight heavy;
      return heavy;
  }
  
  int main()
  {
      auto heavy = MakeHeavy();
      return 0;
  }
  </code></pre>
  <p>I tested this code with VC++11 and GCC 4.71, debug and release (<code>-O2</code>) config. The copy ctor is never called. The move ctor is only called by VC++11 in debug config. Actually, everything seems to be fine with these compilers in particular, but to my knowledge, RVO is optional.</p>
  <p>However, if I explicitly use <code>move</code>:</p>
  <pre><code>HeavyWeight MakeHeavy()
  {
      HeavyWeight heavy;
      return std::move(heavy);
  }
  </code></pre>
  <p>the move ctor is always called. So trying to make it &quot;safe&quot; makes it worse.</p>
  <p>My questions are:</p>
  <ul>
  <li>Why does <code>std::move</code> prevent RVO?</li>
  <li>When is it better to &quot;hope for the best&quot; and rely on RVO, and when should I explicitly use <code>std::move</code>? Or, in other words, how can I let the compiler optimization do its work and still enforce move if RVO is not applied?</li>
  </ul>