Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ where my program "go" after call to list.erase without increment iterator?

Tags:

c++

New to cpp. When I call to erase on iterator without increment it my program exit immediately without any sign or crash. In the following example only 'After if condition ' is printed and than nothing. no error displayed. however if i do the correct call to list.erase(it++); than it print all. my question is about what happened when I don't call it correct. why i don't see any crash or exit? My worried and the reason that i asked the question is about catching these kind of crashes, why i didn't catch it in the catch block? is there a way to catch it?

int main(int argc, char *argv[]) {
    try {
        list<int>::iterator it;
        list<int> list;
        list.push_back(1);
        for (it = list.begin(); it != list.end(); ++it) {
            if ((*it) == 1) {
                list.erase(it);
            }
            cerr << "After if condition " << endl;
        }
        cerr << "After for condition" << endl;
    } catch (...) {
        cerr << "catch exception" << endl;
    }
    cerr << "Finish" << endl;
}
like image 488
Avihai Marchiano Avatar asked Feb 03 '26 12:02

Avihai Marchiano


2 Answers

From std::list::erase():

References and iterators to the erased elements are invalidated.

it is erased, and then used by ++it causing undefined behaviour: meaning anything can happen.

erase() returns the iterator following the last removed element, meaning you can store the return value of erase() and continue but the loop requires modification to avoid skipping an element after an erase() has been executed.

like image 148
hmjd Avatar answered Feb 05 '26 01:02

hmjd


You may not alter the container when using iterators. erase invalidates the iterator immediatley.

What you can do is something like:

for( list<int>::iterator it = list.begin(); it != list.end();)
  if( (*it) == 1 )        
    it=list.erase(it);
  else
    ++it;

(from STL list erase items)

or

for( list<int>::iterator it = list.begin(); it != list.end();)
  if( (*it) == 1 )        
    list.erase(it++);
  else
    ++it;

There are many posts on that. Search for "erase list iterator"!

edit: If you do otherwise, i.e. invalidate the iterator and increasi afterwards, the behaviour is undefined. That means it can differ from system to system, compiler to compiler, run to run.

If it doesn't crash, and gives proper behaviour, you're lucky. If it doesn't crash and does something else, you're unlucky, because it's a hard-to-find bug.

like image 44
steffen Avatar answered Feb 05 '26 01:02

steffen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!