Original Post
Hi, I've decided to give the standard library data structures a try, namely the one for linked lists. Suppose I have a list of pointers, which in turn point to objects on the heap. I want to iterate through the list once per iteration of the main program loop, and for each object that is marked "dead", remove it from the list. However, I'm having trouble deleting the object associated with the current pointer -and- removing the list element (the pointer itself). Here's an example of what I mean: If I leave out that commented line (thingList.erase(iter)), the program dies. While deleting the object that the current pointer points to is great, shouldn't I also remove the list element containing the pointer itself also? Thanks
#include <iostream>
#include <list>
using namespace std;
class Thing
{
public:
Thing() {cout<<"constructor"<<endl;}
~Thing() {cout<<"destructor"<<endl;}
};
int main()
{
list <Thing *> thingList;
Thing *pA = new Thing();
Thing *pB = new Thing();
Thing *pC = new Thing();
Thing *pD = new Thing();
thingList.push_back(pD);
thingList.push_back(pC);
thingList.push_back(pB);
thingList.push_back(pA);
list<Thing *>::iterator iter;
for (iter=thingList.begin(); iter != thingList.end(); iter++)
{
delete *iter;
thingList.erase(iter); //this line crashes the program!
cout<<thingList.size()<<endl;
}
return 0;
}