So, you’ve been working on some piece of code that employs STL containers, specifically a map. Perhaps you’ve also added some multi-threaded flavoring to pack a punch. Great.
Suddenly, you see this:
Debug Assertion Failed!
File: C:\Program Files\Microsoft Visual Studio 8\VC\include\xtree
Expression: map/set iterators incompatible
Strange. What just happened? Did you just mix the iterators of different classes together? No, you’re certain you used map iterators, not set iterators. Everything SEEMS well…
Ah, that’s right. You have an iterator that points to the map’s items, and are indeed iterating over them. The map is protected by a mutex, but – so as to not block for too long – you release and reacquire the mutex every iteration. Another thread then executes and clear()’s the map, rendering your iterator useless. You now compare it to the end() iterator, and voila – crash!
The solution? Make sure you don’t invalidate your iterators while using them. That means – don’t modify the STL container from another thread (even if you are using synchronization mechanisms) if you’re not absolutely certain that you can and that you will not invalidate existing iterators. Operations like insert, erase and clear can invalidate iterators – read the details at each container’s documentation page.