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

Louis Dionne via libcxx-commits libcxx-commits at lists.llvm.org
Mon Sep 15 09:25:52 PDT 2025


================
@@ -2250,6 +2230,63 @@ private:
     return __is_long() ? __get_long_pointer() : __get_short_pointer();
   }
 
+  // Internal buffer management
+  // --------------------------
+  //
+  // These functions are only responsible for managing the buffer itself, not the value inside the buffer. As such,
+  // none of these facilities ensure that there is a null terminator at `data()[size()]`.
+
+  // 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 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())
+      __alloc_traits::deallocate(__alloc_, __get_long_pointer(), __get_long_cap());
+    __rep_.__s = __short();
+  }
+
+  // Replace the current buffer with __alloc; the first __size elements constitute a string
+  _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 void
+  __replace_internal_buffer(__alloc_result __alloc, size_type __size) {
----------------
ldionne wrote:

And now this should take a `__long` instead.

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


More information about the libcxx-commits mailing list