I have a list of pointers to a class cUpdater that have an update method.
class cUpdater
{
public:
virtual Update()=0;
}
list<A*> lpUpdaters;
I want to iterate that list in my main loop and call the update method of the list. So far is easy:
for (list<cA*>::iterator iter(lpUpdaters.begin()); iter!=lpUpdaters.end(); ++iter)
(*iter)->Update();
But the problem starts when inside the update method it removes the updater from the list. As an example, suppose I have a Player inheriting from cUpdater and in the Update method it founds that has being killed, so he remove itself from the list of Updaters.
The problem is that after it returns from the update method the iterator is no longer valid (because it was removed) and the program crash.
The next way make a temporal that solves the problem by moving to the next before it call the update method, so if it gets removed the iterator is still valid
list<cA*>::iterator iter, itemp
for (iter = lpUpdaters.begin(); iter!=lpUpdaters.end();)
{
itemp = iter;
iter++;
(*itemp)->Update();
}
But there is another problem, what about if inside the Update method more than one updater is removed. Take for instance that the player removes itself from the list, plus all its allies.
That is really a problem, because now the next iterator could not be valid when the updater returns.
My question: How to implement the iteration of a list that call the Update method with the condition that inside the Update method new Updaters can be added or removed from the list?
One solution is to each time I want to traverse the list to move them all to a temporal list and keep updating the first one and after that remove it until the list is empty. But that has the disadvantage of all the copies. As this is done several times per frame I need it to be fast. Is there any good way I'm missing?