0

I was trying to erase pointer elements (the value in the map is a pointer) from the map and I saw the code here What happens to an STL iterator after erasing it in VS, UNIX/Linux?

for(map<T, S*>::iterator it = T2pS.begin(); it != T2pS.end(); T2pS.erase(it++)) {
    // wilhelmtell in the comments is right: no need to check for NULL. 
    // delete of a NULL pointer is a no-op.
    if(it->second != NULL) {
        delete it->second;
        it->second = NULL;
    }
}

I am not sure if the 'delete it->second' with de-allocate the correct memory because the erase(it++) step already moves the iterator to the next object. By the time, it reaches the delete statement, it is pointing to the next element which we don't want to delete. Am I missing something?

Community
  • 1
  • 1
vkaul11
  • 4,098
  • 12
  • 47
  • 79

2 Answers2

2

I believe this will work as expected.

The third section of the for loop (where the iterator is erased and then incremented) executes after the first iteration, and so on for each relevant iteration. Thus, you're always erasing the element you've already "dealt with" in the loop contents.

A parallel example:

for (int i = 0; i < 1; ++i) { ...

You will still enter the loop and execute with i = 0 before incrementing i and checking the looping condition.

aardvarkk
  • 14,955
  • 7
  • 67
  • 96
1

You may want to try another way:

while (T2pS.size() > 0) {
  if (T2pS.begin()->second != NULL) {
    delete T2pS.begin()->second;
  }
  T2pS.erase(T2pS.begin());
}
Jeff Jia
  • 172
  • 5