Reputation: 137
I know the 'grammatical why'.
What I'd like to know is, 'techincal why'.
As far as I know, the 'iterator object' is mimic 'pointer'.
If it really mimics 'pointer', it should 'point' the erased index in the container.
Like, if a vector contains
index 0 1 2 3 4
val 10 20 30 40 50
and
vector<int>iterator iter = veciter.begin();
++iter;
veciter.erase(iter);
then the 'iter' should 'point' the 'index 1' which has value of '30' after calling erase if 'iterator object' really mimics 'pointer'.
But it doesn't.
Why?
What's the purpose?
Upvotes: 1
Views: 152
Reputation: 238311
If it really mimics 'pointer', it should 'point' the erased index in the container.
This inference doesn't make sense to me. Pointers are iterators for arrays. It isn't possible to erase elements from arrays, so they cannot be used as an example of how iterators should behave on erasure.
Even if the inference was applicable, you need to understand that iterators are a generalisation of pointers. The intersection of features that are common to all iterators is a subset of features of pointers. It isn't reasonable to assume that all iterators behave the same as pointers in every regard.
why the 'iterator object' becomes invalid after calling 'erase()'?
Because that is the only option that is efficient to implement for all iterators.
Furthermore, iterators are an abstract concept. Try to forget everything about pointers, and concentrate on the following abstract description of iterators: It's an object that refers to an entity, and you can indirect through it (if refers to valid entity) to get an object and you can increment it to move to the next entity (if there is next entity).
Is it intuitive to you that if I refer to something, and that when the referred entity no longer exists, then I am suddenly referring to some other entity? If I indirect through the iterator after the original entity has been destroyed, with the intention of accessing the destroyed entity, then that is a logical error. Getting some other object doesn't improve the situation. Unfortunately though, there isn't an efficient way to generally check for this error either, so it is simple deemed "undefined behaviour".
Since the implementation isn't bound by the standard to return the other object, and is instead free to do whatever, it may attempt to be helpful and detect the error when that is desired (but you cannot rely on that), or it may skip all checks when efficiency is desired in which case the error may cause the program to crash and burn (if you're lucky).
Upvotes: 2