[libcxx-commits] [libcxx] [libc++][NFC] Use early returns in basic_string::operator= (PR #137145)

Nikolas Klauser via libcxx-commits libcxx-commits at lists.llvm.org
Thu Apr 24 02:23:40 PDT 2025


https://github.com/philnik777 created https://github.com/llvm/llvm-project/pull/137145

This makes the code a lot easier to read.


>From 8a714a71cf305c1f97eccc3a7eb8eb1e82349de1 Mon Sep 17 00:00:00 2001
From: Nikolas Klauser <nikolasklauser at berlin.de>
Date: Thu, 24 Apr 2025 11:23:06 +0200
Subject: [PATCH] [libc++][NFC] Use early returns in basic_string::operator=

---
 libcxx/include/string | 32 +++++++++++++++-----------------
 1 file changed, 15 insertions(+), 17 deletions(-)

diff --git a/libcxx/include/string b/libcxx/include/string
index e7e541e31432d..fb2bee9d1a251 100644
--- a/libcxx/include/string
+++ b/libcxx/include/string
@@ -2867,23 +2867,21 @@ basic_string<_CharT, _Traits, _Allocator>::operator=(value_type __c) {
 template <class _CharT, class _Traits, class _Allocator>
 _LIBCPP_CONSTEXPR_SINCE_CXX20 _LIBCPP_STRING_INTERNAL_MEMORY_ACCESS basic_string<_CharT, _Traits, _Allocator>&
 basic_string<_CharT, _Traits, _Allocator>::operator=(const basic_string& __str) {
-  if (this != std::addressof(__str)) {
-    __copy_assign_alloc(__str);
-    if (!__is_long()) {
-      if (!__str.__is_long()) {
-        size_type __old_size = __get_short_size();
-        if (__old_size < __str.__get_short_size())
-          __annotate_increase(__str.__get_short_size() - __old_size);
-        __rep_ = __str.__rep_;
-        if (__old_size > __get_short_size())
-          __annotate_shrink(__old_size);
-      } else {
-        return __assign_no_alias<true>(__str.data(), __str.size());
-      }
-    } else {
-      return __assign_no_alias<false>(__str.data(), __str.size());
-    }
-  }
+  if (this == std::addressof(__str))
+    return *this;
+
+  __copy_assign_alloc(__str);
+
+  if (__is_long())
+    return __assign_no_alias<false>(__str.data(), __str.size());
+
+  if (__str.__is_long())
+    return __assign_no_alias<true>(__str.data(), __str.size());
+
+  __annotate_delete();
+  auto __guard = std::__make_scope_guard(__annotate_new_size(*this));
+  __rep_ = __str.__rep_;
+
   return *this;
 }
 



More information about the libcxx-commits mailing list