Date: Tue, 9 Dec 2025 21:53:16 +0300
On 8 Dec 2025 17:45, Nikl Kelbon via Std-Proposals wrote:
> The standard needs to better clarify the section on vector iterator
> invalidation.
>
> *Why i think its important:*
>
> Some implementations added checks like: "oh, we must store all .end()
> iterators into global map under mutex and mark them invalid on each
> push_back, it will be SO useful for our developers!"
> So, minimal example where it breaks completely:
>
> std::vector<int> v;
> v.reserve(10);
>
> v.push_back(1);
>
> auto b = v.begin();
> auto e = v.end();
> v.push_back(1);
> ++b;
> REQUIRE(b == e); // assertion failure:
> // _STL_VERIFY(this->_Getcont() == _Right._Getcont(), "vector iterators
> incompatible");
>
>
> Its common pattern when using vector to reserve memory and push values,
> there are no "better way to do it", thats why it must be valid
I don't think the claim that the end iterator must not be invalidated by
push_back follows from the usage pattern with pre-reserving storage.
However, the behavior you want can be achieved with indices instead of
iterators. More so, this will consistently work regardless of whether
reallocation happens, and it will also work with deque and other
containers supporting element indices.
> The standard needs to better clarify the section on vector iterator
> invalidation.
>
> *Why i think its important:*
>
> Some implementations added checks like: "oh, we must store all .end()
> iterators into global map under mutex and mark them invalid on each
> push_back, it will be SO useful for our developers!"
> So, minimal example where it breaks completely:
>
> std::vector<int> v;
> v.reserve(10);
>
> v.push_back(1);
>
> auto b = v.begin();
> auto e = v.end();
> v.push_back(1);
> ++b;
> REQUIRE(b == e); // assertion failure:
> // _STL_VERIFY(this->_Getcont() == _Right._Getcont(), "vector iterators
> incompatible");
>
>
> Its common pattern when using vector to reserve memory and push values,
> there are no "better way to do it", thats why it must be valid
I don't think the claim that the end iterator must not be invalidated by
push_back follows from the usage pattern with pre-reserving storage.
However, the behavior you want can be achieved with indices instead of
iterators. More so, this will consistently work regardless of whether
reallocation happens, and it will also work with deque and other
containers supporting element indices.
Received on 2025-12-09 18:53:19
