c++ - Why does vector::pop_back invalidate the iterator (end() - 1)? -


note: question applies erase, too. see bottom.


what's reason behind fact end() - 1 iterator invalidated after pop_back called on vector?

to clarify, i'm referring situation:

std::vector<int> v; v.push_back(1); v.push_back(2);  std::vector<int>::iterator i1 = v.begin(), i2 = v.end() - 1, i3 = v.begin() + 1;  v.pop_back();  // i1 still valid // i2 invalid // i3 invalid  std::vector<int>::iterator i4 = v.end();  assert(i2 == i4);  // undefined behavior (but why should be?!) assert(i3 == i4);  // undefined behavior (but why should be?!) 

why happen? (i.e. when invalidation ever prove beneficial implementation?)

(note isn't theoretical problem. visual c++ 2013 -- , 2012 -- display error if try in debug mode, if have _iterator_debug_level set 2.)


regarding erase:

note same question applies erase:
why erase(end() - 1, end()) invalidate end() - 1?

(so please don't say, "pop_back invalidates end() - 1 because equivalent calling erase(end() - 1, end())"; that's begging question.)

the interesting question mean iterator invalidated. , don't have answer standard. know extent standard considers iterator not pointer location inside container, rather proxy particular element lives within container.

with in mind, after erasing of single element in middle of vector, iterators after point of removal become invalidated no longer refer same element referred before.

support line of reasoning comes iterator invalidation clauses of other operations in container. example, on insert, standard guarantees if there no reallocation iterators before point of insertion remain valid. exceptio probat regulam in casibus non exceptis, invalidates iterators after point of insertion.

if validity of iterators related fact there element of container iterator points, none of iterators invalidated operation (again, in absence of reallocations).

going further in line of reasoning, if consider iterator validity pointer validity, none of iterators vector invalidated during erase operation. end()-1 iterator become non-dereferencable, remain valid, not case.


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -