Avoid bad iterator with static list

Hey, yet another quick question... I'll spend an hour helping on the beginner forum afterward.

I have the following class which forces dynamic memory management and can perform actions on all instances at once using a list...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class entity{
private:
    std::list<entity*>::iterator _entityIterator;
    static std::list<entity*> _entityList;

    entity(){
        _entityIterator = _entityList.insert(_entityList.end(), this);
    }

    ~entity(){
        _entityList.erase(_entityIterator);
    }
    
public:
    static entity* instance(){ return new entity(); }
    void destroy(){ delete this; }

    virtual void update(){}
    static void updateAll();
}


Now I wanted to make the updateAll() method like this
1
2
3
for(auto it = _entityList.begin(); it != _entityList.end(); ++it){
    (**it).update();
}


But I realized that if the inheriting class destroys the object in the update method, the iterator it will not be valid anymore.

I thought about making the destroy() method return the next iterator just like the actual std::list::erase() does, but I don't think it's a good choice because then it gives public access to the iterator.

The solution I found is this:
1
2
3
4
5
6
7
std::list<entity*>::iterator i, j;
    i = _entityList.begin();
    while(i != _entityList.end()){
        j = i;
        ++i;
        (**j).update();
    }

This way the potentially wrong iterator is discarded after the update() call.

But I actually have multiple methods in my class, each with a somethingAll() equivalent. Is there another way I should do this, because right now I need the exact same loop in all somethingAll() methods.

Thanks already if you took the time to read all this!
1
2
3
for(auto it = _entityList.begin(); it != _entityList.end(); /* ++it */ ){
    (**it++).update();
}
Oh, off course!
That's a great example of where you put the ++ matters. Not sure why I didn't think of this, probable because I didn't do enough stuff with iterators yet. Thanks! If you keep answering my questions like this I'll have to add you to the credits of my project :)
Topic archived. No new replies allowed.