Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 809
Paul Jurczak Avatar asked Feb 17 '16 21:02

Paul Jurczak


1 Answers

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)

like image 152
Slava Avatar answered Sep 20 '22 15:09

Slava