[libcxx-commits] [libcxx] Refactor vector constructors to eliminate code duplication (PR #113193)

via libcxx-commits libcxx-commits at lists.llvm.org
Mon Oct 21 10:16:24 PDT 2024


https://github.com/winner245 created https://github.com/llvm/llvm-project/pull/113193

This PR refactors the `std::vector`'s initializer_list constructors `vector(initializer_list<value_type> __il, const allocator_type& __a)` and `vector(initializer_list<value_type> __il)` to reduce code duplication. The constructors now call `__init_with_size` directly, reducing code duplication and improving readability and maintainability.

>From e9ec47b71e2a714717ef8d8d075f5c4475d1e5ae Mon Sep 17 00:00:00 2001
From: Peng Liu <winner245 at hotmail.com>
Date: Mon, 21 Oct 2024 13:08:52 -0400
Subject: [PATCH] Refactor vector's initializer_list constructors to eliminate
 code duplication

---
 libcxx/include/vector | 14 ++------------
 1 file changed, 2 insertions(+), 12 deletions(-)

diff --git a/libcxx/include/vector b/libcxx/include/vector
index dc31f31838264c..5ee2ca52752e23 100644
--- a/libcxx/include/vector
+++ b/libcxx/include/vector
@@ -1292,24 +1292,14 @@ vector<_Tp, _Allocator>::vector(vector&& __x, const __type_identity_t<allocator_
 template <class _Tp, class _Allocator>
 _LIBCPP_CONSTEXPR_SINCE_CXX20 inline _LIBCPP_HIDE_FROM_ABI
 vector<_Tp, _Allocator>::vector(initializer_list<value_type> __il) {
-  auto __guard = std::__make_exception_guard(__destroy_vector(*this));
-  if (__il.size() > 0) {
-    __vallocate(__il.size());
-    __construct_at_end(__il.begin(), __il.end(), __il.size());
-  }
-  __guard.__complete();
+  __init_with_size(__il.begin(), __il.end(), __il.size());
 }
 
 template <class _Tp, class _Allocator>
 _LIBCPP_CONSTEXPR_SINCE_CXX20 inline _LIBCPP_HIDE_FROM_ABI
 vector<_Tp, _Allocator>::vector(initializer_list<value_type> __il, const allocator_type& __a)
     : __alloc_(__a) {
-  auto __guard = std::__make_exception_guard(__destroy_vector(*this));
-  if (__il.size() > 0) {
-    __vallocate(__il.size());
-    __construct_at_end(__il.begin(), __il.end(), __il.size());
-  }
-  __guard.__complete();
+  __init_with_size(__il.begin(), __il.end(), __il.size());;
 }
 
 #endif // _LIBCPP_CXX03_LANG



More information about the libcxx-commits mailing list