[libcxx-commits] [libcxx] [libc++][string] Fixes shrink_to_fit. (PR #97961)

Louis Dionne via libcxx-commits libcxx-commits at lists.llvm.org
Mon Jul 15 09:11:39 PDT 2024


================
@@ -3265,23 +3265,38 @@ basic_string<_CharT, _Traits, _Allocator>::__shrink_or_extend(size_type __target
     __p        = __get_long_pointer();
   } else {
     if (__target_capacity > __cap) {
+      // Extend
+	  // - called from reserve should propagate the exception thrown.
       auto __allocation = std::__allocate_at_least(__alloc(), __target_capacity + 1);
       __new_data        = __allocation.ptr;
       __target_capacity = __allocation.count - 1;
     } else {
+      // Shrink
+      // - called from shrink_to_fit should not throw.
+      // - called from reserve may throw but is not required to.
 #ifndef _LIBCPP_HAS_NO_EXCEPTIONS
       try {
 #endif // _LIBCPP_HAS_NO_EXCEPTIONS
         auto __allocation = std::__allocate_at_least(__alloc(), __target_capacity + 1);
+
+#ifdef _LIBCPP_HAS_NO_EXCEPTIONS
+        if (__allocation.ptr == nullptr)
----------------
ldionne wrote:

I don't think `ptr` can ever be `null`. When we fail to allocate inside `operator new`, we throw `bad_alloc` or `bad_array_new_length` depending on the mechanism. But we never actually return `nullptr`. We used to return `nullptr` under `-fno-exceptions` and I suspect that's how we got this branch in the first place, but it seems incorrect now.

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


More information about the libcxx-commits mailing list