Here is my code:
void SurfaceManager::SurfaceManagerDelete()
{
for(map<string,SurfaceManager*>::iterator Iter = SurfaceList.begin(); Iter != SurfaceList.end(); ++Iter)
{
delete (*Iter).second;
(Iter) = SurfaceList.erase(Iter);
}
SurfaceList.clear();
}
Why does this cause several memory leaks when I scan it with VLD? I know it has something to do with the way I’m deleting the memory from an element specifically this line “(Iter) = SurfaceList.erase(Iter);”, however I would like to know why, and how I’m supposed to properly delete elements from the list.
The problem is the ++Iter in the for-loop. That’s because
already updates Iter to point to the element after the erased one, like an increment.
So the ++Iter then skips another element, effectively you end up deleting every other element!