3

I followed the following post that illustrates the scenario how iterator behaves after some non-const operations.

Iterator invalidation rules

I have problems to understand the difference between reference and iterator. Here is one of the rule listed as an example for clarification:

deque: all iterators and references are invalidated, unless the inserted member is at an end (front or back) of the deque (in which case all iterators are invalidated, but references to elements are unaffected) [23.2.1.3/1]

Here is the sample code that is based on the reference.

std::deque<int> mydeque;
mydeque.push_back(1);
mydeque.push_back(2);
mydeque.push_back(3);

const int& int3 = mydeque.back();                     // reference to 3
      int& int3 = mydeque.back();
std::deque<int>::iterator itBack = mydeque.crbegin(); // pointing to 3

mydeque.push_back(4);

Question> If my vague understanding is correct, then the following statement is true:

After the calling of the line of `mydeque.push_back(4)`
`int3` is still valid because it is a reference to element.
`itBack` is invalidated because it is an iterator.

Thank you

Community
  • 1
  • 1
q0987
  • 34,938
  • 69
  • 242
  • 387

1 Answers1

1

Yes, that sounds correct. The reason the iterator gets invalidated but the reference does not is that the iterator needs to be able to do ++ and -- correctly, but pushing something onto a deque might cause it to rearrange its structures for tracking that. But, deque guarantees it won't move the elements themselves, even if it has to restructure the container around them.

This suggests that the implementation of deque has an additional level of indirection built into its iterators that it hides from you. But, that's pretty much the entire the point of iterators, and why they're distinct from references.

Joe Z
  • 17,413
  • 3
  • 28
  • 39