c++ - Does std::vector::erase() really invalidate the iterator at the point of erase? -


i playing around understand iterator invalidation rule. however, when run following code in c++14 compiler, output confuses me..

std::vector<int> test = {1,2,3}; auto = test.begin() + 1; test.erase(it); std::cout << *it << std::endl; 

output = 3 shouldn't invalidate @ point? why seems jump next pos? many in advance

dereferencing invalidated iterator has undefined results. program may crash, may stop runtime error or break in debugger (if running debug build debug version of stl iterator debugging/validation) , may "seem work", i.e., deliver value erased collection.

this because iterators may implemented pointers. not case, defining behavior in situation undefined allows such efficient , simple implementation. invalid iterators implemented pointers may still point valid memory location, may still contain value contained, though logically no longer part of data structure (collection) part of. there no validation code checks if iterator valid when dereferenced (except in debug builds).

this both 1 of characteristics strengths , 1 of weaknesses of c++, gives program better performance @ cost of stability , security in case program undefined (due bug or using unvalidated user input).


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -