[libcxx-commits] [libcxx] [libc++] Use relocation in vector::emplace_back (PR #159365)

Louis Dionne via libcxx-commits libcxx-commits at lists.llvm.org
Wed Sep 17 09:57:35 PDT 2025


================
@@ -1188,19 +1188,43 @@ _LIBCPP_CONSTEXPR_SINCE_CXX20 inline
     void
 #endif
     vector<_Tp, _Allocator>::emplace_back(_Args&&... __args) {
-  pointer __end = this->__end_;
-  std::__if_likely_else(
-      __end < this->__cap_,
-      [&] {
-        __emplace_back_assume_capacity(std::forward<_Args>(__args)...);
-        ++__end;
-      },
-      [&] { __end = __emplace_back_slow_path(std::forward<_Args>(__args)...); });
-
-  this->__end_ = __end;
+  if constexpr (__libcpp_is_trivially_relocatable<value_type>::value &&
+                __allocator_has_trivial_move_construct_v<allocator_type, value_type> &&
+                __allocator_has_trivial_destroy_v<allocator_type, value_type>) {
+    union _Tmp {
+      _LIBCPP_CONSTEXPR_SINCE_CXX20 _Tmp() {}
+      _LIBCPP_CONSTEXPR_SINCE_CXX20 ~_Tmp() {}
+      value_type __val_;
+    };
+    _Tmp __tmp;
+
+    __alloc_traits::construct(__alloc_, std::addressof(__tmp.__val_), std::forward<_Args>(__args)...);
----------------
ldionne wrote:

We need a test that triggers this code path and the construction throws. Also we need a test with this code path where the reallocation throws, such that if we didn't have the `__guard` then we'd fail the test.

https://github.com/llvm/llvm-project/pull/159365


More information about the libcxx-commits mailing list