List begin iterator invalidation

Hello!

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

Consider the following code:

#include
#include

int main() {
std::list l;
std::list::iterator it = l.begin();
l.push_back(0);
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 (https://stackoverflow.com/questions/59974821/validity-of-list-begin-iterator-after-insertion) 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