I have two methods.
When you call an object to be deleted, it really sets two flags:
1.One to tell the container that an object has been deleted
2.One to tell the container which objects have been requested to be deleted
void object::deleteObject()
{
container->objectHasBeenDeleted = true;
isToDelete = true;
}
One
Using a vector of objects
std::vector<object*> objects;
Then in the update function, check to see if an object has been deleted and if so iterate through all the objects and remove the ones that have a delete flag
void container::update()
{
if (objectHasBeenDeleted)
{
std::vector<object*>::iterator ListIterator;
for(ListIterator=objects.begin(); ListIterator!=objects.end();)
{
if( (*ListIterator)->isToDelete )
{
ListIterator = objects.erase(ListIterator);
delete *ListIterator;
}
else {
++ListIterator;
}
}
objectHasBeenDeleted = false;
}
}
Two
Using a (pointer to a) vector of objects.
std::vector<object*> *objects;
In the update function, if an object is to be deleted, iterate through the objects and add the ones that aren't to be deleted to a new vector. delete the objects vector and set the pointer to the new vector
void container::update()
{
if (objectHasBeenDeleted)
{
std::vector<object*> *newVector;
unsigned long i;
for (i = 0; i < objects->size(); i++)
{
if (!objects->at(i)->isToDelete)
{
newVector->push_back(objects->at(i));
}
}
delete objects;
objects = newVector;
objectHasBeenDeleted = false;
}
}