C++ Logo

std-proposals

Advanced search

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

From: Arthur O'Dwyer <arthur.j.odwyer_at_[hidden]>
Date: Sun, 31 Mar 2024 12:05:41 -0400
On Sun, Mar 31, 2024 at 11:22 AM Avi Kivity via Std-Proposals <
std-proposals_at_[hidden]> wrote:

>
> std::vector<int> v;
> v.push_back(41);
> v.push_back(v.back());
>
> The second push_back() can cause the vector to reallocate.
>

Yes, and implementations jump through hoops to make this work.
If reallocation is necessary in this case, what we'll do is:
- Allocate the new buffer of size 2.
- Construct the new element (`41`) into the new buffer. (If this throws,
deallocate the old buffer.)
- Move `41` from the old buffer to the new buffer. (This can't throw.)
- Destroy the old element and deallocate the old buffer.

If instead of `int` you'd used a type that can't be nothrow moved, then
we'd do:
- Allocate the new buffer of size 2.
- Construct the new element (`41`) into the new buffer. (If this throws,
deallocate the old buffer.)
- Copy `41` from the old buffer to the new buffer. (If this throws, destroy
the new element and deallocate the old buffer.)
- Destroy the old element and deallocate the old buffer.

Reallocation on `insert`-into-the-middle-of-a-vector is generally done
something like the same way: Construct the new element *first*, then move
the old elements around it.

–Arthur

Received on 2024-03-31 16:05:54