0

What happens to an iterator if the container that it iterates over is changed?

Here is the code:

#include <iostream>
#include <vector>

int main() {
    std::vector<int> v = {1,2,3};
    std::vector<int>::iterator it = v.begin();
    std::cout << *it << '\n';
    it++;
    std::cout << *it << '\n';
    v.emplace_back(4);
    it++;
    std::cout << *it << '\n';
    it++;
    std::cout << *it << '\n';

    return 0;
}

output:

1
2
12230672 // every time you run you get a different value.
0
Keloo
  • 1,368
  • 1
  • 17
  • 36
  • It becomes invalid. That is stated in many places. E.g.: – JHBonarius Dec 03 '19 at 19:08
  • @Keloo No, it is not necessary to delete this question. Duplicate questions are good for SEO. – Xirema Dec 03 '19 at 19:11
  • 1
    Note that "just changing" the underlying container does not necessarily invalidate an iterator. It depends on the change. – Marshall Clow Dec 03 '19 at 19:11
  • What happens if you are in a range loop and the container is changed by another thread? (the reason why I'm asking) – Keloo Dec 03 '19 at 19:13
  • 1
    @Keloo If you read any variable while a different thread is changing it, you get undefined behavior. – HolyBlackCat Dec 03 '19 at 19:14
  • 1
    @Keloo If you have a substantially different question you need to ask, you should post it as a new question, instead of trying to iterate on versions of the question in comments. – Xirema Dec 03 '19 at 19:17

1 Answers1

2

The iterator is invalidated. That means (tautology alert!) that it is no longer valid, and indirecting through it is undefined behavior.

This can happen for a vector when appending (in your case, via emplace_back) causes the internal storage for the vector to be reallocated.

See the draft standard for more.

Marshall Clow
  • 15,972
  • 2
  • 29
  • 45
  • strictly speaking this is wrong for `emplace_back`. Iterators are only invalidated when the new size() is greater than capacity(), if not only the `end` iterator is invalidated.. or cppreference is wrong, which is of course possible... – 463035818_is_not_an_ai Dec 03 '19 at 19:15