title: Why is it unsafe to call push_back in a for loop even when there is no memory reallocation?
body: <p>When I read this post: <a href="https://stackoverflow.com/a/42448319/3336423">https://stackoverflow.com/a/42448319/3336423</a></p>
  
  <p>I understand, that calling push_back in a for loop is unsafe because:</p>
  
  <blockquote>
    <p>If the new size() is greater than capacity() then all iterators and
    references (including the past-the-end iterator) are invalidated.
    Otherwise only the past-the-end iterator is invalidated.</p>
  </blockquote>
  
  <p>Then, I assume that if I guarantee the capacity won't be exceeded, it would be safe....</p>
  
  <p>But apparently not, all implementations below will crash after first <code>push_back</code> is called (using Visual Studio), even if I can see that capacity remains unchanged within the loop (so I assume the vector does not reallocate its memory):</p>
  
  <p><strong>Version1:</strong></p>
  
  <pre><code>std::vector&lt;int&gt; v1{ 3, 4, 5 };
  v1.reserve( v1.size()*2 );
  size_t c1 = v1.capacity();
  for ( auto val : v1 )
  {
      v1.push_back( val );
      c1 = v1.capacity();
  }
  </code></pre>
  
  <p><strong>Version2:</strong></p>
  
  <pre><code>std::vector&lt;int&gt; v2{ 3, 4, 5 };
  v2.reserve( v2.size()*2 );
  size_t c2 = v2.capacity();
  auto curEnd = v2.end();
  for ( auto iter = v2.begin(); iter != curEnd; ++iter )
  {
      v2.push_back( *iter );
      c2 = v2.capacity();
  }
  </code></pre>
  
  <p><strong>Version3:</strong></p>
  
  <pre><code>std::vector&lt;int&gt; v3{ 3, 4, 5 };
  v3.reserve( v3.size()*2 );
  size_t c3 = v3.capacity();
  for ( auto iter = v3.begin(); iter != v3.end(); ++iter )
  {
      v3.push_back( *iter );
      c3 = v3.capacity();
  }
  </code></pre>
  
  <p>What makes those code crash?</p>