C++11 forward_list iterator remains pointing to removed value

An iterator remains to point to the element it previously did and the value it points to is not removed from memory. I wonder how can this be explained? Thank you.

forward_list<int> Fwdl {46, 21, 88, 901, 404};
auto it = Fwdl.begin();


cout << "List : "; for(int& elem : Fwdl) cout << " " << elem; cout << endl;

//This prints "List : 21 88 901 404" as expected, but:

cout << "Iterator is alive! " << *it << endl;

//This still prints "Iterator is alive! 46"


N4431 - list operations [list.ops] (emphasize mine)

void remove(const T& value);
template <class Predicate> void remove_if(Predicate pred);

Effects: Erases all the elements in the list referred by a list iterator i for which the following conditions hold: *i == value, pred(*i) != false. Invalidates only the iterators and references to the erased elements.

What you have is a typical manifestation of undefined behaviour and you should not rely on such code.

What probably happens is something similar to this:

int* p = new int(42);
int* iterator = p;
delete p;

// may still display 42, since the memory may have not yet been reclaimed by the OS, 
// but it is Undefined Behaviour
std::cout << *iterator; 

As said in one of the comments, it is undefined behavior to dereference an invalidated iterator. In your case it was probably still pointing to the space on the heap where the element used to be, and hasn't been overwritten by something else yet. On a different compiler, or a different run of the program it could have been jibbersish or crashed the program entirely.

Need Your Help

HTML meta keyword/description element, useful or not?

html seo

Does filling out HTML meta description/keyword tags matter for SEO?