how about you keep one copy of the container and use it exclusively for iterators.
this maybe the only way to make sure iterators do not crash your code.
java does it this way.
How does it handle erasing by iterators or iterators range? For instance, container.erase(container.begin(), container.begin()+5);
How would you determine if the iterator has to be invalidated or not? Perhaps an iterator is only invalidated if the value it is pointing to is deleted?
This is hard to do in general and it will usually lead to iteration over all iterators to see what must be done about each one. There are some guarantees on the validity of iterators after calling some methods that modify the container. A rather messy document available at
http://www.open-std..../2010/n3225.pdf tries to sum them up in the chapter 23. For example, a swap() never invalidates the iterators (though of course after the call they point to different containers, and all GC references have to be updated anyway). An erase() on an associative container invalidates only the erased iterator - however there might still exist other copies of it, so again we have to iterate and check each one. A push_back() or pop_back() on a deque does not invalidate anything. A range erase() on a vector invalidates only the iterators past the new end. In this last case it is possible to verify an iterator at any point - it is sufficient that it lies between [begin(), end()) range since vector never shrinks the underlying array, excepting clear() call, which invalidates everything (in any other container too).
The need for iteration on almost every modification is one of the arguments for the "versioned containers" solution. But perhaps some hybrid approach wouldn't be a bad idea - in some cases we know that we have to invalidate everything (any clear()) and we do that by increasing the version counter, sometimes we handypick the iterators to be invalidated (erase(iterator) in map or set), and in case of a vector, maybe we don't care for invalidation and check the validity runtime (it entails but a pair of address comparisons, so the performance hit should not be severe).
I will take some time to think more about this. I am gone for good until 18.07 so I just wanted to pour all my thoughts here first.