STL containers have the problem that iterators can be invalidated when the container changes. Would it be possible for the container to announce that it has changed by adding a call has_changed()?
It is common to query empty() before certain operations. If the container set a bool on operations that would affect iterators like insert() or erase() then it would be possible to query has_changed() before reusing an iterator.
Crazy?
EDIT Thanks for a bunch of good replies and food for thought. I wish I could award more than one winner.
The (approximate) way fail-fast iterators work in Java is that the container increments a counter each time it changes. The iterators copy this counter on creation, and increment it each time the container is changed through them. If the iterator detects a mismatch, it throws an exception.
C++ has the exciting property that some operations invalidate some iterators on the container, but not others. For example, assuming sufficient space has been reserved
vector::insertinvalidates iterators after the insertion point, but not before.Another difficult case is
list::remove. This leaves all iterators valid except the one removed, and all copies of it.As you can imagine, it would be pretty difficult to track this precisely. What happens in practice is that your implementation might offer debug options in which iterators will do their best to detect whether they’re valid or not. This might depend on implementation details of whether they’ll currently “work”, though, rather than on whether the standard guarantees that they still work.
It would be possible to do something in C++ similar to the “version number” in Java, but it would give false positives of iterators which appear invalid but in fact are valid.