"JustSomeGuy" <bo*******@yahoo.com> wrote in
news:11**********************@g49g2000cwa.googlegr oups.com:
I have a method which traverses a list and then clears it.
I was optimizing it and broke it.
series *Ser;
series::iterator im_it;
for (im_it=Ser->begin(); im_it != Ser->end(); ++im_it)
{
img = *im_it;
...
}
Ser->clear();
vs. (Which dies a horrible death on the last element.)
for (im_it=Ser->begin(); im_it != Ser->end(); Ser->pop_front())
{
img = *im_it;
...
}
I'm somewhat surprised that it didn't blow up on the first element.
You've invoked undefined behaviour by destroying the object that the
iterator refers to. Let's rewrite your for loop to its equivalent while
loop:
im_it=Ser->begin();
while (im_it != Ser->end())
{
img = *im_it;
...
Ser->pop_front();
}
So, before pop_front is called, im_it is an iterator to the first element
in the list. After calling pop_front, that iterator is now invalidated.
Attempting to use it for anything is undefined behaviour.
Probably a better optimization would be:
while (!Ser->emtpy())
{
img = Ser->front();
...
Ser->pop_front();
}