Skip to content

Commit d3b9855

Browse files
authored
Add exception guard for constructor vector(n, x, a) (llvm#113086)
Added exception guard to the `vector(n, x, a)` constructor to enhance exception safety. This change ensures that the `vector(n, x, a)` constructor is consistent with other constructors, such as `vector(n)`, `vector(n, x)`, `vector(n, a)`, in terms of exception safety.
1 parent 828467a commit d3b9855

File tree

2 files changed

+10
-0
lines changed

2 files changed

+10
-0
lines changed

libcxx/include/__vector/vector.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,10 +165,12 @@ class _LIBCPP_TEMPLATE_VIS vector {
165165
_LIBCPP_CONSTEXPR_SINCE_CXX20 _LIBCPP_HIDE_FROM_ABI
166166
vector(size_type __n, const value_type& __x, const allocator_type& __a)
167167
: __alloc_(__a) {
168+
auto __guard = std::__make_exception_guard(__destroy_vector(*this));
168169
if (__n > 0) {
169170
__vallocate(__n);
170171
__construct_at_end(__n, __x);
171172
}
173+
__guard.__complete();
172174
}
173175

174176
template <class _InputIterator,

libcxx/test/std/containers/sequences/vector/vector.cons/exceptions.pass.cpp

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,14 @@ int main(int, char**) {
139139
check_new_delete_called();
140140
#endif // TEST_STD_VER >= 14
141141

142+
try { // Throw in vector(size_type, value_type, const allocator_type&) from the type
143+
int throw_after = 1;
144+
ThrowingT v(throw_after);
145+
std::vector<ThrowingT> vec(1, v, std::allocator<ThrowingT>());
146+
} catch (int) {
147+
}
148+
check_new_delete_called();
149+
142150
try { // Throw in vector(InputIterator, InputIterator) from input iterator
143151
std::vector<int> vec((Iterator<std::input_iterator_tag>()), Iterator<std::input_iterator_tag>(2));
144152
} catch (int) {

0 commit comments

Comments
 (0)