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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With