C++ Logo


Advanced search

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

From: Giuseppe D'Angelo <giuseppe.dangelo_at_[hidden]>
Date: Sun, 31 Mar 2024 17:54:23 +0200
Il 31/03/24 17:22, Avi Kivity via Std-Proposals ha scritto:
> Is this undefined behavior? Should it be specified to work? Should it be
> noted that it is dangerous?

It's required to work because there's nothing that says that it doesn't
work. (*)

This isn't just about push_back when capacity is full; you could
insert() in the middle of a vector, copy-constructing from an element of
the same vector _after_ the insert position. Vector cannot just "create
a hole" and then construct in there, as it has to deal with this
aliasing possibility.

Implementations take lots of precautions to make this work (... they
take an extra copy / construct a temporary, if they detect the
"danger"). For instance, search for "_Temporary_value" in:

> https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/bits/vector.tcc

(*) Note that if you call the push_back overload taking an rvalue, for
instance by doing v.push_back(std::move(v[42])), then you run afoul of
library UB. https://eel.is/c++draft/res.on.arguments#1.3

Giuseppe D'Angelo

Received on 2024-03-31 15:54:26