[libcxx-commits] [libcxx] [libc++] Optimize basic_string::operator= (PR #224535)

Louis Dionne via libcxx-commits libcxx-commits at lists.llvm.org
Thu Sep 24 06:23:56 PDT 2026


================
@@ -2727,28 +2727,40 @@ basic_string<_CharT, _Traits, _Allocator>::__grow_by_without_replace(
 
 template <class _CharT, class _Traits, class _Allocator>
 template <bool __is_short>
-_LIBCPP_CONSTEXPR_SINCE_CXX20 _LIBCPP_NOINLINE basic_string<_CharT, _Traits, _Allocator>&
+_LIBCPP_CONSTEXPR_SINCE_CXX20 _LIBCPP_NOINLINE void
 basic_string<_CharT, _Traits, _Allocator>::__assign_no_alias(const value_type* __s, size_type __n) {
   const auto __cap  = __is_short ? static_cast<size_type>(__min_cap) : __get_long_cap();
-  const auto __size = __is_short ? __get_short_size() : __get_long_size();
   if (__n >= __cap) {
-    __grow_by_and_replace(__cap - 1, __n - __cap + 1, __size, 0, __size, __n, __s);
-    return *this;
+    return [] [[__gnu__::__noinline__]] (basic_string& __this, const value_type* __ls, size_type __ln) static {
+      std::__assume(__this.__is_long() == !__is_short);
+      std::__assume(!__alloc_traits::is_always_equal::value || __ln <= __this.max_size());
+      __this.__annotate_delete();
+      if _LIBCPP_CONSTEXPR (!__is_short)
+        __alloc_traits::deallocate(__this.__alloc_, __this.__get_long_pointer(), __this.__get_long_cap());
+      auto __guard   = std::__make_exception_guard([&] {
+        if _LIBCPP_CONSTEXPR (!__is_short)
+          __this.__rep_ = __rep();
+      });
----------------
ldionne wrote:

Is this exception guard optimized out when the string is short? Answer: yes it is.

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


More information about the libcxx-commits mailing list