[libcxx-commits] [libcxx] [libc++] Refactor memory allocation in basic_string (PR #128423)

Louis Dionne via libcxx-commits libcxx-commits at lists.llvm.org
Wed Sep 10 09:33:26 PDT 2025


================
@@ -2250,6 +2229,73 @@ private:
     return __is_long() ? __get_long_pointer() : __get_short_pointer();
   }
 
+  // Internal buffer management
+  // --------------------------
+
+  // Allocate a buffer of __capacity size with __alloc and return it
+  _LIBCPP_HIDE_FROM_ABI static _LIBCPP_CONSTEXPR_SINCE_CXX20 __alloc_result
+  __allocate_long_buffer(_Allocator& __alloc, size_type __capacity) {
+    auto __buffer = std::__allocate_at_least(__alloc, __recommend(__capacity) + 1);
+
+    if (__libcpp_is_constant_evaluated()) {
+      for (size_type __i = 0; __i != __buffer.count; ++__i)
+        std::__construct_at(std::addressof(__buffer.ptr[__i]));
+    }
+
+    return __buffer;
+  }
+
+  // Deallocate __allocation using __alloc
+  _LIBCPP_HIDE_FROM_ABI static _LIBCPP_CONSTEXPR_SINCE_CXX20 void
+  __deallocate_long_buffer(_Allocator& __alloc, __alloc_result __allocation) {
+    __alloc_traits::deallocate(__alloc, __allocation.ptr, __allocation.count);
+  }
+
+  // deallocate the long buffer if it exists and clear the short buffer so we are an empty string
+  _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 void __reset_internal_buffer() {
+    __annotate_delete();
+    if (__is_long())
+      __deallocate_long_buffer(__alloc_, __get_internal_long_buffer());
+    __rep_.__s = __short();
+  }
+
+  // get the internal buffer allocation
+  // THis assumes that there is in fact an allocation
+  _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 __alloc_result __get_internal_long_buffer() {
----------------
ldionne wrote:

If we remove `__deallocate_long_buffer`, then this function also doesn't really have a purpose anymore, so I'd remove it.

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


More information about the libcxx-commits mailing list