Is it possible that inserting and/or erasing elements can invalidate iterators to existing elements.
Thank you.
Yes. The documentation for boost::ptr_vector<T>
states:
A
ptr_vector<T>
is a pointer container that uses an underlyingstd::vector<void*>
to store the pointers.
And inserting elements into or erasing elements from a std::vector
can cause re-allocation and therefore existing iterators to be invalidated.
Specifically, §23.3.6.5/3 of C++11 states about erase()
:
(3) Effects: Invalidates iterators and references at or after the point of the erase.
and about insert()
and push_back()
:
(1) Remarks: Causes reallocation if the new size is greater than the old capacity. If no reallocation happens, all the iterators and references before the insertion point remain valid.
Therefore, to prevent iterator invalidation in the case of element insertion, you may use the reserve()
function to increase the vector's capacity before obtaining any iterators from it. Those iterators will then remain valid until the size()
of the vector exceeds the number of elements space was reserved for.