C++ Logo

std-proposals

Advanced search

Re: [std-proposals] vector::push_back must not invalidate past-the-end iterator

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Mon, 8 Dec 2025 12:59:50 -0500
On Mon, Dec 8, 2025 at 9:45 AM Nikl Kelbon via Std-Proposals
<std-proposals_at_[hidden]> 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

1. Is this actually a "common pattern"? The core of your proposal
relies on accepting the idea that a lot of people do this even though
it's formally UB. Do you have any evidence of it beyond your own code?
2. Would it actually make sense if a user were to rely on it?

There is no other container where getting an end iterator and
inserting an element into the end of the container would *ever* leave
that end iterator to be pointing to something valid. Not `list`, not
`deque`, not `map`, nothing. The only container where this would even
potentially be implementable is `vector` (or similar containers).

So why should an exception be made for `vector`?

Received on 2025-12-08 18:00:05