Victor Bazarov wrote:
Pete C wrote: Victor Bazarov wrote: std::vector<int>::iterator it = v.begin();
-- it;
Bam!!! 'it' is now _invalid_.
Do you not get undefined behaviour at this point? Are you saying that
if we did "exit(0);" now, the program would be OK? I didn't realise
that.
Invalidation of an iterator is a normal thing. Undefined behaviour
occurs when you try to _use_ an invalid iterator.
-- it;
BANG!!! Undefined behaviour. Everything after that is irrelevant.
Here, decrementing means using. You need to know its value to give
it a new one. But evaluating the iterator when it's invalid is not
defined.
Nope, it isn't. This is intentional; it allows for e.g. simple linked
list
implementations. The first iterator will have list::iterator::prev==0,
and --it; translates to it = *(it.prev);.
Else, you should be able to decrement it N times, increment it N times,
and get back to begin. Logically, that means the iterator would have to
store N (which is a large overhead for single-linked lists)
Furthermore,
it would be very tricky to keep such an N-before-begin iterator valid
if
one inserts an element at the begin of such a list.
Lots of pain, little gain: a good reason to disallow the creation of
such
invalid iterators altogether. After all, it's equally invalid for
arrays, and we
could handle those as well.
HTH,
Michiel Salters
HTH,
Michiel Salters.