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;
}
You may not alter the container when using iterators.
eraseinvalidates the iterator immediatley.What you can do is something like:
(from STL list erase items)
or
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.