C++ Logo


Advanced search

[std-proposals] When does vector::push_back() invalidation happen?

From: Avi Kivity <avi_at_[hidden]>
Date: Sun, 31 Mar 2024 18:22:05 +0300

std::vector<int> v;

The second push_back() can cause the vector to reallocate. If it
reallocates before executing the push_back(), then performs the
push_back(), then it will use-after-free its argument. If it
reallocates after the push_back(), and the move constructor can throw,
then we lose the strong exception guarantee.

The standard says:
> Remarks: Causes reallocation if the new size is greater than the old
capacity. Reallocation invalidates all the references, pointers, and
iterators referring to the elements in the sequence, as well as the
past-the-end iterator.

So, it says nothing about whether a push_back referring to a vector
element is legal.

Is this undefined behavior? Should it be specified to work? Should it
be noted that it is dangerous?

Received on 2024-03-31 15:22:09