'Is it legal to add elements to a preallocated vector in a range-based for loop over that vector?

I'm using Visual Studio 2015 Update 1 C++ compiler and this code snippet:

#include <iostream>
#include <vector>

using namespace std;

int main()
{
  vector<int> v{3, 1, 4};

  v.reserve(6);

  for (auto e: v)
    v.push_back(e*e);

  for (auto e: v)
    cout << e << " ";

  return 0;
}

Release version runs fine, but debug version produces vector iterators incompatible error message. Why is that?

Before you flag it as a duplicate question to Add elements to a vector during range-based loop c++11, please read my answer https://stackoverflow.com/a/35467831/219153 with arguments to the contrary.



Solution 1:[1]

According to documentation:

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.

It says even if capacity is enough past-the-end iterator is invalidated, so I believe your code has undefined behavior (unless this documentation is incorrect and standard says otherwise)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mariano Desanze