Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

list

stl

erase

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?

like image 650
Kiril Kirov Avatar asked Mar 11 '11 14:03

Kiril Kirov


1 Answers

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.

like image 82
Vlad Avatar answered Sep 29 '22 19:09

Vlad