At this line:
auto it = l.begin();
There is nothing in the list yet, so the beginning is also the end.
std::list::emplace()
inserts items before the given iterator, so this line:
l.emplace(it, 0);
Places 0
before it
, ie it inserts at the end of the list.
std::list
also has some of the most forgiving iterator invalidation rules, and the it
iterator is not invalidated as items are inserted into the list. it
continues to refer to the end of the list as new items are added to the list.
Ultimately, this line:
cout << *it << endl;
Dereferences the "end" iterator, and this is not allowed. The results are undefined, and in this case it appears to contain the value 3. Maybe if you add another item then it'll appear to contain 4, and maybe you're seeing a hidden implementation-specific detail of the list
. Or maybe the computer will crash or get a bad case of the nasal demons.