Search code examples
c++liststlerase

Doesn't erasing std::list::iterator invalidates the iterator and destroys the object?


Why does the following print 2?

list<int> l;
l.push_back( 1 );
l.push_back( 2 );
l.push_back( 3 );
list<int>::iterator i = l.begin();
i++;
l.erase( i );
cout << *i;

I know what erase returns, but I wonder why this is OK? Or is it undefined, or does it depend on the compiler?


Solution

  • Yes, it's undefined behaviour. You are dereferencing a kind of wild pointer. You shouldn't use the value of i after erase.

    And yes, erase destructs the object pointed to. However, for POD types destruction doesn't do anything.

    erase doesn't assign any special "null" value to the iterator being erased, the iterator is just not valid any more.