grayasm
grayasm

Reputation: 993

std::list.unique() should invalidate iterators?

I have this code:

#include <iostream>
#include <list>

int main()
{    
    typedef std::list<int> list;
    int i0t[5]={-1, 2, 3, 3, 5};
    list list_1(i0t, i0t+5);
    list::reverse_iterator ri0 = ++list_1.rbegin();    
    list_1.unique();
    list_1.remove(3);
    int val = *ri0; // why is this valid ?
    std::cout << "val = " << val << "\n";
    return 0;
}

My intuition was that ri0 iterator would become invalid after
list_1.unique();
list_1.remove(3);
using MS VS2005 Debug configuration with _HAS_ITERATOR_DEBUGGING=1
However, I think "iterator debugging" didn't catch this. Right ?

Thank you.

Upvotes: 2

Views: 92

Answers (2)

Captain Obvlious
Captain Obvlious

Reputation: 20103

23.3.5.5/15 states that the effects of a remove operation performed on a list will only invalidate iterators and references to erased elements. It does not specify that the operation must invalidate those iterators. The iterator remaining valid is unspecified behavior and is not guaranteed to occur in other implementations. Accessing the iterator after the modification however is undefined behavior.

Upvotes: 1

awesoon
awesoon

Reputation: 33701

My intuition was that ri0 iterator would become invalid

Yes, it would. Per § 23.3.5.5

void remove(const T& value)

void unique()

[...] Invalidates only the iterators and references to the erased elements.

So, behavior of your program is undefined.

Upvotes: 4

Related Questions