Search code examples
c++c++11iteratorforward-list

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();

Fwdl.remove(46);

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"

Solution

  • N4431 - 23.3.5.5/15 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;