[libc++] [LIBCXX-DEBUG-FIXME] Fix an iterator-invalidation issue in string::assign.
authorArthur O'Dwyer <arthur.j.odwyer@gmail.com>
Tue, 27 Apr 2021 13:10:04 +0000 (09:10 -0400)
committerArthur O'Dwyer <arthur.j.odwyer@gmail.com>
Wed, 5 May 2021 20:20:53 +0000 (16:20 -0400)
This appears to be a bug in our string::assign: when assigning into
a longer string, from a shorter snippet of itself, we invalidate
iterators before doing the copy. We should invalidate them afterward.
Also drive-by improve the formatting of a function header.

Differential Revision: https://reviews.llvm.org/D101675

libcxx/include/string
libcxx/test/std/strings/basic.string/string.modifiers/string_assign/iterator.pass.cpp

index d233369..db29f21 100644 (file)
@@ -1763,11 +1763,7 @@ basic_string<_CharT, _Traits, _Allocator>::__invalidate_all_iterators()
 template <class _CharT, class _Traits, class _Allocator>
 inline
 void
-basic_string<_CharT, _Traits, _Allocator>::__invalidate_iterators_past(size_type
-#if _LIBCPP_DEBUG_LEVEL == 2
-                                                                        __pos
-#endif
-                                                                      )
+basic_string<_CharT, _Traits, _Allocator>::__invalidate_iterators_past(size_type __pos)
 {
 #if _LIBCPP_DEBUG_LEVEL == 2
     __c_node* __c = __get_db()->__find_c_and_lock(this);
@@ -1787,6 +1783,8 @@ basic_string<_CharT, _Traits, _Allocator>::__invalidate_iterators_past(size_type
         }
         __get_db()->unlock();
     }
+#else
+    (void)__pos;
 #endif // _LIBCPP_DEBUG_LEVEL == 2
 }
 
@@ -2361,12 +2359,11 @@ basic_string<_CharT, _Traits, _Allocator>::assign(size_type __n, value_type __c)
         size_type __sz = size();
         __grow_by(__cap, __n - __cap, __sz, 0, __sz);
     }
-    else
-        __invalidate_iterators_past(__n);
     value_type* __p = _VSTD::__to_address(__get_pointer());
     traits_type::assign(__p, __n, __c);
     traits_type::assign(__p[__n], value_type());
     __set_size(__n);
+    __invalidate_iterators_past(__n);
     return *this;
 }
 
@@ -2498,13 +2495,12 @@ basic_string<_CharT, _Traits, _Allocator>::assign(_ForwardIterator __first, _For
             size_type __sz = size();
             __grow_by(__cap, __n - __cap, __sz, 0, __sz);
         }
-        else
-            __invalidate_iterators_past(__n);
         pointer __p = __get_pointer();
         for (; __first != __last; ++__first, ++__p)
             traits_type::assign(*__p, *__first);
         traits_type::assign(*__p, value_type());
         __set_size(__n);
+        __invalidate_iterators_past(__n);
     }
     else
     {