Check this code:
#include "stdafx.h"
#include <list>
int _tmain(int argc, _TCHAR* argv[])
{
std::list<int> mylist;
mylist.push_back(1);
std::list<int>::iterator i = mylist.end();
if( i == mylist.end() )
printf( "end is end\n" );
mylist.clear();
if( i == mylist.end() )
printf( "never get here because Microsoft seems to "
"think the iterator is no longer safe.\n" );
return 0;
}
Now, according to cplusplus.com this shouldn’t be a problem, and in release mode, I think this is fine and doesn’t cause any issues really, but debugging becomes impossible as this just bails without letting me continue. Any pointers?
Other answers point out that, in general, you can’t rely on a container’s past-the-end iterator remaining valid when the container is cleared. However, the past-the-end iterator of a list should indeed remain valid:
The past-the-end iterator does not refer to any element, so should not be invalidated.