Fix unsafe vector assignment operations during reallocations #5107
+291
−57
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Current implementations of vector assignment operations, including the copy, move,
initializer_list
-assignment operators, as well as all overloads of theassign
functions and the C++23assign_range
function, are unsafe during reallocations triggered by assignments. This unsafety can lead to a broken vector with all elements erased, as reported in issue #5106.The issue arises because all the assignment functions ultimately execute the following code during reallocations on assignments:
This sequence is unsafe because the destruction of the old vector occurs strictly before the construction of the new vector elements. If any exception is raised during the subsequent construction of new elements, the original vector is already cleared and there is no way to recover it.
This patch fixes #5106 using a copy-and-swap idiom, ensuring that the vector remains intact in the event of exceptions during vector reallocations in assignments. In other words, this patch enhances the copy/initializer_list-assignment operators, the
assign
overloads, and C++23assign_range
ofstd::vector
to provide strong exception guarantees during vector reallocations. However, it should be noted that in general, these assignment operations cannot always guarantee strong exception safety.