Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector iterator not dereferencable?

I'm getting that error with this code:

for(std::vector<AguiTimedEvent*>::iterator it = timedEvents.begin();
    it != timedEvents.end();)
{
    if((*it)->expired())
    {
        (*it)->timedEventCallback();
        delete (*it);

        it = timedEvents.erase(it);
    }
    else
        it++;
}

What could be the problem?

the timed event sometimes pushes a new one in when its callback is called, that might do it

Thanks

like image 953
jmasterx Avatar asked Dec 21 '10 23:12

jmasterx


1 Answers

If you are looping through a vector and the callback function causes the vector to be added to, then all iterators into the vector may be invalidated including the loop variable it.

In this case (where the callback modifies the vector) you are probably better off using an index as your loop variable.

You probably need to do some thorough analysis of the design to make sure that you aren't going to create any unexpected infinite loops.

E.g.

for(std::vector<AguiTimedEvent*>::size_type n = 0;
    n < timedEvents.size();)
{
    if(timedEvents[n]->expired())
    {
        timedEvents[n]->timedEventCallback();
        delete timedEvents[n];

        timedEvents.erase(timedEvents.begin() + n);
    }
    else
        n++;
}
like image 71
CB Bailey Avatar answered Oct 14 '22 18:10

CB Bailey