28
votes

Regarding this question on iterator invalidation rules, it seems obvious that the spirit of the standard means, for example, that "an erase in the middle of the deque invalidates all the iterators and references to elements of the deque" also refers to the end iterator.

However, I can't find anywhere that the standard makes this explicit, and strictly speaking the end iterator is not an iterator to an element in the container.

Does the 2003 standard make this clear somewhere?

1
For example, 23.1/10: no swap() function invalidates any references, pointers, or iterators referring to the elements of the containers being swapped. [ Note: The end() iterator does not refer to any element, so it may be invalidated. —end note ] ... I do not know if we can be certain that iterator referring to an element has been used consistently in the Standard to exclude end iterators :/Matthieu M.
Cannot find any paragraph distinguishing end from other iterators. end() returns an iterator which is the past-the-end value for the container. That's all. Gee.user703016
I don't have the 2003 standard to hand, but C++0x seems to be clear on this, e.g. "An erase operation that erases the last element of a deque invalidates only the past-the-end iterator and all iterators and references to the erased elements." (emphasis mine).Mike Seymour
@MarkRansom: Of course. That's not what this question is about, though.Lightness Races in Orbit
@Johannes: I suppose if the end iterator points to a sentinel value within the container, then the end iterators after the swap won't point to the sentinel in the "right" container, thus any sequence [it, end) would be ill-formed as end would not be reachable from it.Matthieu M.

1 Answers

9
votes

For example, 23.1/10:

no swap() function invalidates any references, pointers, or iterators referring to the elements of the containers being swapped. [ Note: The end() iterator does not refer to any element, so it may be invalidated. —end note ]

I do not know if we can be certain that iterator referring to an element has been used consistently in the Standard to exclude end iterators :/

As said in a comment, I suppose this is to allow end iterators pointing to sentinel values within the container.

For example, a typical doubly linked List implementation is to create a Node structure, and have one Node by value within the List to act as the end node.