C++ Logo

std-proposals

Advanced search

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

From: Tiago Freire <tmiguelf_at_[hidden]>
Date: Sun, 31 Mar 2024 15:51:56 +0000
I don’t know how it could push before reallocating if reallocating needs to take place. I.e. you don’t have the space to put the new element so where are you going to put it?

Regarding your question, its all references, there are no copies up until when the element is inserted onto the new location, that this should be considered dangerous seems to me to be a no-brainer. But I don’t think it requires any further explanation.
It should be seen as any different to:

Int& temp = v.back();
v.push_back(temp);


Best regards,

From: Std-Proposals <std-proposals-bounces_at_[hidden]> On Behalf Of Avi Kivity via Std-Proposals
Sent: Sunday, March 31, 2024 5:22 PM
To: std-proposals <std-proposals_at_[hidden]>
Cc: Avi Kivity <avi_at_[hidden]>
Subject: [std-proposals] When does vector::push_back() invalidation happen?

Consider:

std::vector<int> v;
v.push_back(41);
v.push_back(v.back());

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:52:02