I have a standard vector of pointers.
Under what circumstances might an iterator into this vector become invalidated?
I have reason to believe that when an object is deleted, any vector iterator referencing it is thereby invalidated. This does not seem correct to me, however. I do believe this would be the standard behavior of containers in Managed .NET, but this seems off to me in c++.
for (It = Vec.begin(); It != Vec.end(); It++){
GoToOtherCode((*It));
}
function GoToOtherCode (ObjectType* Obj){
delete Obj;
}
Should this invalidate the Iterator It? It doesn’t seem to me that it should not, but then I’m stuck with a difficult issue to debug! (I’m scared of my workaround — to iterate through the vector with via integer-index. (This works fine… I’m just afraid of why the above is causing invalidation issues).
Thanks in advance for your time.
Edit: Thanks for the advice. The general consensus is that the above code is dangerous, but that it will not invalidate the Iterator. I believe I encountered an error with Visual Studio 2008 debugger, because after opening the project the next day, this invalidate issue was gone. So — as with many things in computers, if nothing else seems to work, try resetting the thing.
It won’t invalidate the iterator, it’s actually the way you would delete heap allocated objects that are owned by the vector, the clear() method won’t do that for you. This is pretty common:
Perfectly fine if you don’t attempt to use what you just deleted.