0

Say I have a simple program as so:

int main(void) {
  std::list<int> l;
  auto it = l.begin();
  auto it2 = l.insert(l.begin(), 5);
  std::cout << (it == it2) << std::endl;
}

Doesn't this show that the iterator it has been invalidated by inserting into the list. Yet the C++ standard says that insertion into a list does not invalidate iterators.

Originally it would probably hold a nullptr since the list was empty. Now it no longer points to any iterator part of the list. So is it not invalidated?

Raees Rajwani
  • 487
  • 5
  • 18
  • 4
    `auto it = l.begin();` returns `std::list::end()` as the container is currently empty. You can never have a item inserted at this position; so the test will always fail. `it` remains a valid iterator. – Richard Critten Jul 23 '18 at 18:18
  • 2
    Basically if you print `(it == l.end())` instead, the program outputs 1. – jcai Jul 23 '18 at 18:21
  • 2
    As @RichardCritten pointed out `it == l.end()`, while `it2` will [point to the inserted item](https://en.cppreference.com/w/cpp/container/list/insert). So the result you're getting is what would be expected. No iterators are invalidated here. "Doesn't this show that the iterator it has been invalidated by inserting into the list." No, it does not show that. – Fred Larson Jul 23 '18 at 18:22
  • 1
    @Arcinde: You are correct, and notably it's the same *before and after the insert*. – Fred Larson Jul 23 '18 at 18:25
  • Re: "Originally `it` would probably hold a nullptr since the list was empty." Probably not. But it doesn't matter, so long as the requirements for iterators are satisfied. – Pete Becker Jul 23 '18 at 19:12

0 Answers0