[libc-commits] [libc] [libc][cpp::string] Do not count null terminator in capacity() (PR #211918)

Jackson Stogel via libc-commits libc-commits at lists.llvm.org
Fri Jul 24 14:57:28 PDT 2026


================
@@ -142,19 +154,24 @@ class string {
     return string_view(buffer_, size_);
   }
 
-  LIBC_INLINE void reserve(size_t new_capacity) {
-    ++new_capacity; // Accounting for the terminating '\0'
-    if (new_capacity <= capacity_)
+  LIBC_INLINE void reserve(size_t new_cap) {
+    size_t allocation_size = new_cap + 1; // +1 for terminating '\0'
+    if (allocation_size <= capacity_)
       return;
+
     // We extend the capacity to amortize buffer_ reallocations.
     // We choose to augment the value by 11 / 8, this is about +40% and division
     // by 8 is cheap. We guard the extension so the operation doesn't overflow.
-    if (new_capacity < SIZE_MAX / 11)
-      new_capacity = new_capacity * 11 / 8;
+    if (allocation_size < SIZE_MAX / 11)
+      allocation_size = allocation_size * 11 / 8;
+
+    bool is_empty_string = buffer_ == get_empty_string();
----------------
jtstogel wrote:

Done

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


More information about the libc-commits mailing list