title: Why does reallocating a vector copy instead of moving the elements?
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/8001823/how-to-enforce-move-semantics-when-a-vector-grows">How to enforce move semantics when a vector grows?</a>  </p>
  </blockquote>
  
  
  
  <p><code>insert</code>, <code>push_back</code> and <code>emplace</code>(<code>_back</code>) can cause a reallocation of a <code>std::vector</code>. I was baffled to see that the following code <em>copies</em> the elements instead of <em>moving</em> them while reallocating the container.</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;vector&gt;
  
  struct foo {
      int value;
  
      explicit foo(int value) : value(value) {
          std::cout &lt;&lt; "foo(" &lt;&lt; value &lt;&lt; ")\n";
      }
  
      foo(foo const&amp; other) noexcept : value(other.value) {
          std::cout &lt;&lt; "foo(foo(" &lt;&lt; value &lt;&lt; "))\n";
      }
  
      foo(foo&amp;&amp; other) noexcept : value(std::move(other.value)) {
          other.value = -1;
          std::cout &lt;&lt; "foo(move(foo(" &lt;&lt; value &lt;&lt; "))\n";
      }
  
      ~foo() {
          if (value != -1)
              std::cout &lt;&lt; "~foo(" &lt;&lt; value &lt;&lt; ")\n";
      }
  };
  
  int main() {
      std::vector&lt;foo&gt; foos;
      foos.emplace_back(1);
      foos.emplace_back(2);
  }
  </code></pre>
  
  <p>On my specific machine using my specific compiler (GCC 4.7) this prints the following:</p>
  
  <pre><code>foo(1)
  foo(2)
  foo(foo(1))
  ~foo(1)
  ~foo(1)
  ~foo(2)
  </code></pre>
  
  <p>However, when deleting the copy constructor (<code>foo(foo const&amp;) = delete;</code>), the following (expected) output is generated:</p>
  
  <pre><code>foo(1)
  foo(2)
  foo(move(foo(1))
  ~foo(1)
  ~foo(2)
  </code></pre>
  
  <p>Why is that? Would’t moving generally be more efficient, or at least not much less efficient, than copying?</p>
  
  <p>It bears noting that <a href="http://ideone.com/2EPxu" rel="noreferrer">GCC 4.5.1 does the expected thing</a> – is this a regression in GCC 4.7 or is it some deviously clever optimisation because the compiler sees that my object is cheap to copy (but how?!)?</p>
  
  <p>Also note that I made sure that this <em>is</em> caused by reallocation, by experimentally putting a <code>foos.reserve(2);</code> in front of the insertions; this causes neither copy nor move to be executed.</p>