List begin iterator invalidation


I’ve stumbled upon a peculiarity with lists which I haven’t been able to explain so far.

Consider the following code:


int main() {
std::list l;
std::list::iterator it = l.begin();
l.insert(it, 1);
for(const int &i: l) {
printf("%d", i);

This will print “01”. I fail to understand why the 1 is inserted at the end. I would expect that the begin iterator would stay valid across the push_back. For the record, g++ seems to have the same behavior.

I’ve already created a stack overflow question around this ( and asked in the llvm IRC channel about it. So far without having an explanation. So now I’m turning to you.

Thank you in advance

Alexander Torstling