Reputation: 51
I am trying to delete a node in a linked list using mylist.erase(); but the node remains in the list. I tried to use delete() but the program crashes. Any idea?
list <Person*> :: iterator it;
it = gamelist.begin(); //gamelist is a <Person*> list. it is an iterator to this list.
while (it!=gamelist.end()){
if ((*it)->is_dead == true) {
delete (*it); //if I comment this line the program does not crash but the "dead" Person still remains in the list.
it = gamelist.erase(it);
}
else ++it;
}
Upvotes: 3
Views: 126
Reputation: 238321
Deleting a pointer has no effect on whether the pointer remains in a container. Since you haven't shown a program that demonstrates that shows that the node remains in the list, I posit that it does not remain after the call to erase
.
If you allocated the pointed object with new
, then you must delete
it at some point. If the program crashes when you delete the pointer here, that means that either
new
.It is not possible to "test" the validity of the pointer within the program (except for checking whether it is null, but deleting null is OK and would not crash, so that's not the problem in your case). You must analyze your program and guarantee the validity yourself. Smart pointers make reasoning about the validity of pointers far easier. I recommend you to use them.
Upvotes: 4