[PATCH][_GLIBCXX_DEBUG] Fix _Safe_iterator copy/move semantic PR 127540

François Dumont frs.dumont@gmail.com
Thu Nov 5 19:41:05 GMT 2026


Following completion of the 23_containers and 24_iterators tests in 
C++98, C++11 and C++26 this is a slightly modified version.

There was a build issue in C++98.

On 11/5/26 00:30, Jonathan Wakely wrote:
> On Wed, 4 Nov 2026 at 20:59, François Dumont <frs.dumont@gmail.com> wrote:
>> Hi
>>
>> Here is what I propose to do.
>>
>>       libstdc++: Fix _Safe_iterator copy/move semantic [PR127540]
>>
>>       Currently our safe iterators for debug mode fail to meet the
>> requirement
>>       that they have a "valid but unspecified" state after being moved from.
>>       They have a singular and non-copyable state, which means they cannot be
>>       copied or passed around by value. This is non-conforming.
>>
>>       Define the moved-from state for our safe iterators to be the same as
>>       their value-initialized state. This means they are copyable after being
>>       moved from.
>>
>>       The downside of this change is that we no longer diagnose equality
>>       comparison with a moved-from iterator, which is undefined behaviour.
>>       Because value-initialized iterators can be compared, our moved-from
>>       iterators are now also comparable. This seems like an acceptable
>>       compromise in order to support copying them (which needs to work).
>>
>>       If we care about diagnosing invalid comparisons, we would need to
>>       introduce a new moved-from state to the iterators. That could then be
>>       checked in the iterator's constructors and assignment operators so that
>>       moved-from iterators are allowed as the source of those operations. The
>>       new state would not be checked in comparisons so that using them would
>>       abort, as was the case before this commit, e.g.
>>
>> /home/jwakely/gcc/17/include/c++/17.0.0/debug/safe_iterator.h:546:
>>         In function:
>>             constexpr bool gnu_debug::operator==(const
>> _Safe_iterator<gnu_cxx::
>>             normal_iterator<int*, std::vector<int, std::allocator<int> >
>>   >, std::
>>             debug::vector<int>, std::forward_iterator_tag>::_Self&, const
>>             _Safe_iterator<gnu_cxx::normal_iterator<int*, std::vector<int,
>>             std::allocator<int> > >, std::debug::vector<int>,
>>             std::forward_iterator_tag>::_Self&)
>>
>>         Error: attempt to compare a singular iterator to a
>> dereferenceable iterator.
>>
>>       Reviewing this behavior also implement properly all the possible
>> copy/move
>>       instantiations or assignment operations so that only the necessary
>> is done.
> What does "only the necessary" mean? This is a fairly large and
> complex patch which does a lot more than just removing some bad
> assertions.
I will refine this part of the ChangeLog.
>
> This definitely isn't suitable for backporting, so what would be the
> minimal fix suitable for backporting? Your earlier patch?

This is clearly not suitable for backport.

I replied to your RFC here:

https://gcc.gnu.org/pipermail/libstdc++/2026-October/068084.html

To tell that you should go ahead with this minimal change to fix PR127540.

Without any reply on the PR I thought that you were happy waiting for 
this much bigger change so I kept the PR in reference.

But I'll be more than happy to remove it and treat it as a pure 
enhancement patch.


>
>
>>       This is a good optimization allowing several tests timeout-ing on
>> build to now pass.
>>
>>       Those operations are also, when involving a singular iterator,
>> properly copying
>>       the source state so that using the resulting iterator will emit the
>> same assertion
>>       as if the original iterator had been used.
>>
>>       libstdc++-v3/ChangeLog:
>>
>>               PR libstdc++/127540
>>               * include/debug/safe_base.h
>>               (_Safe_iterator_base): Remove implicit C++20 constexpr
>> qualification.
>>               (_Safe_iterator_base::operator=(const
>> _Safe_iterator_base&)): New, default.
>>               (_Safe_iterator_base::_M_get_sequence): New, get sequence
>> pointer if not singular.
>>               (_Safe_iterator_base::_M_inplace_attach): New.
>>               (_Safe_iterator_base(const _Safe_iterator_base&, bool)):
>> Only copy input
>>               _Safe_iterator_base _M_sequence and _M_version if singular
>> without attaching.
>>               * include/debug/safe_iterator.h:
>>               (_Safe_iterator(const _Safe_iterator&)): Forward to latter
>> _Safe_iterator_base
>>               constructor.
>>               (_Safe_iterator<_MutableIte>(const _Safe_iterator<>&)):
>> Likewise.
>>               (_Safe_iterator): Add friend declaration to access mutable
>> iterator members
>>               from the immutable type.
>>               (_Safe_iterator::_M_copy_state): New.
>>               (_Safe_iterator::_M_move): New, make moved instance
>> value-initialized.
>>               (_Safe_iterator(_Safe_iterator&&, bool)): New.
>>               (_Safe_iterator(_Safe_iterator&&)): Forward to latter.
>> (_Safe_iterator<_MutableIte>(_Safe_iterator<_MutableIte, _Seq, _Cat>&&)):
>>               Likewise.
>>               (_Safe_iterator::_M_copy_assign<_Ite>): New.
>>               (_Safe_iterator::operator=(const _Safe_iterator&)): Call
>> latter.
>>               (_Safe_iterator::operator=<_MutableIte>(const
>> _Safe_iterator<>&)): New, likewise.
>>               (_Safe_iterator::_M_move_assign): New.
>>               (_Safe_iterator::operator=(_Safe_iterator&&)): Call latter.
>> (_Safe_iterator::operator=<_MutableIte>(_Safe_iterator<>&&)): New, likewise.
>>               (_Safe_iterator::_M_attach): Remove.
>>               (_Safe_iterator::_M_attach_single): Remove.
>>               * src/c++11/debug.cc (_Safe_iterator_base::_M_attach): Do
>> not reset _M_version
>>               if attaching to a null sequence.
>>               * testsuite/24_iterators/debug/safe_iterator.cc: New test.
>>
>> 23_containers/vector/* tested with _GLIBCXX_DEBUG mode.
>>
>> Ok to commit after C++98 tests run for all 23_containers tests ?
>>
>> François
>>
>> On 10/29/26 23:05, François Dumont wrote:
>>> Hi
>>>
>>> Here is what I've come up with so far.
>>>
>>> This is clearly not limited to fix of PR 127540 but it does fix it.
>>>
>>> This is a big performance improvement for the _GLIBCXX_DEBUG mode. The
>>> proof is that I managed to run testsuite/23_containers/flat_* tests.
>>> They were all timeout-ing on my laptop without the patch.
>>>
>>> I still need to work on the ChangeLog entry which I copied from your
>>> RFC Jonathan.
>>>
>>> I've also prepared the same for _Safe_local_iterator.
>>>
>>> Happy to have some feedback.
>>>
>>>      libstdc++: Fix _Safe_iterator copy/move semantic PR 127540
>>>
>>>      Currently our safe iterators for debug mode fail to meet the
>>> requirement
>>>      that they have a "valid but unspecified" state after being moved
>>> from.
>>>      They have a singular and non-copyable state, which means they
>>> cannot be
>>>      copied or passed around by value. This is non-conforming.
>>>
>>>      Define the moved-from state for our safe iterators to be the same as
>>>      their value-initialized state. This means they are copyable after
>>> being
>>>      moved from.
>>>
>>>      The downside of this change is that we no longer diagnose equality
>>>      comparison with a moved-from iterator, which is undefined behaviour.
>>>      Because value-initialized iterators can be compared, our moved-from
>>>      iterators are now also comparable. This seems like an acceptable
>>>      compromise in order to support copying them (which needs to work).
>>>
>>>      If we care about diagnosing invalid comparisons, we would need to
>>>      introduce a new moved-from state to the iterators. That could then be
>>>      checked in the iterator's constructors and assignment operators so
>>> that
>>>      moved-from iterators are allowed as the source of those
>>> operations. The
>>>      new state would not be checked in comparisons so that using them
>>> would
>>>      abort, as was the case before this commit, e.g.
>>>
>>> /home/jwakely/gcc/17/include/c++/17.0.0/debug/safe_iterator.h:546:
>>>        In function:
>>>            constexpr bool gnu_debug::operator==(const
>>> _Safe_iterator<gnu_cxx::
>>>            normal_iterator<int*, std::vector<int, std::allocator<int> >
>>>> , std::
>>>            debug::vector<int>, std::forward_iterator_tag>::_Self&, const
>>>            _Safe_iterator<gnu_cxx::normal_iterator<int*, std::vector<int,
>>>            std::allocator<int> > >, std::debug::vector<int>,
>>>            std::forward_iterator_tag>::_Self&)
>>>
>>>        Error: attempt to compare a singular iterator to a
>>> dereferenceable iterator.
>>>
>>>      libstdc++-v3/ChangeLog:
>>>
>>>              PR libstdc++/127540
>>>              * config/abi/pre/gnu.ver (GLIBCXX_3.4.37): Add
>>> _Safe_sequence_base::_M_attach
>>>              and _Safe_sequence_base::_M_attach_single symbols so that
>>> freshly instantiated
>>>              safe iterators can be attached without going through a
>>> detach attempt.
>>>              * include/debug/safe_base.h
>>>              (_Safe_iterator_base): Remove implicit C++20 constexpr
>>> qualification.
>>>              (_Safe_iterator_base::operator=(const
>>> _Safe_iterator_base&)): New, default.
>>>              (_Safe_iterator_base::_M_get_sequence): New, get sequence
>>> pointer if not singular.
>>>              (_Safe_iterator_base::_M_attach_only): New.
>>>              (_Safe_iterator_base(const _Safe_sequence_base*, bool)):
>>> Use latter.
>>>              (_Safe_iterator_base(const _Safe_iterator_base&, bool)):
>>> Likewise and only copy
>>>              input _Safe_iterator_base _M_sequence and _M_version if
>>> singular.
>>>              * include/debug/safe_iterator.h:
>>>              (_Safe_iterator(const _Safe_iterator&)): Forward to latter
>>> _Safe_iterator_base
>>>              constructor.
>>>              (_Safe_iterator<_MutableIte>(const _Safe_iterator<>&)):
>>> Likewise.
>>>              (_Safe_iterator): Add friend declaration to access mutable
>>> iterator members
>>>              from the immutable type.
>>>              (_Safe_iterator::_M_move): New, make moved instance
>>> value-initialized.
>>>              (_Safe_iterator(_Safe_iterator&&, bool)): New.
>>>              (_Safe_iterator(_Safe_iterator&&)): Forward to latter.
>>> (_Safe_iterator<_MutableIte>(_Safe_iterator<_MutableIte, _Seq, _Cat>&&)):
>>>              Likewise.
>>>              (_Safe_iterator::_M_copy_assign<_Ite>): New.
>>>              (_Safe_iterator::operator=(const _Safe_iterator&)): Call
>>> latter.
>>>              (_Safe_iterator::operator=<_MutableIte>(const
>>> _Safe_iterator<>&)): New, likewise.
>>>              (_Safe_iterator::_M_move_assign): New.
>>>              (_Safe_iterator::operator=(_Safe_iterator&&)): Call latter.
>>> (_Safe_iterator::operator=<_MutableIte>(_Safe_iterator<>&&)): New,
>>> likewise.
>>>              (_Safe_iterator::_M_attach): Remove.
>>>              (_Safe_iterator::_M_attach_single): Remove.
>>>              * src/c++11/debug.cc (_Safe_iterator_base::_M_attach): Do
>>> not reset _M_version
>>>              if attaching to a null sequence.
>>>              (_Safe_iterator_base::_M_attach_single): Likewise.
>>>              * testsuite/24_iterators/debug/safe_iterator.cc: New test.
>>>
>>> Tested under Linux x86_64 23_containers and 24_iterators tests.
>>>
>>> François
-------------- next part --------------
diff --git a/libstdc++-v3/include/debug/safe_base.h b/libstdc++-v3/include/debug/safe_base.h
index 776b86ee701..bc313c70ea6 100644
--- a/libstdc++-v3/include/debug/safe_base.h
+++ b/libstdc++-v3/include/debug/safe_base.h
@@ -79,9 +79,11 @@ namespace __gnu_debug
 
   protected:
     /** Initializes the iterator and makes it singular. */
-    _GLIBCXX20_CONSTEXPR
     _Safe_iterator_base() = default;
 
+    _Safe_iterator_base&
+    operator=(const _Safe_iterator_base&) = default;
+
     /** Initialize the iterator to reference the sequence pointed to
      *  by @p __seq. @p __constant is true when we are initializing a
      *  constant iterator, and false if it is a mutable iterator. Note
@@ -94,19 +96,14 @@ namespace __gnu_debug
     : _Safe_iterator_base()
     {
       if (!std::__is_constant_evaluated())
-	this->_M_attach(__seq, __constant);
+	_M_attach(__seq, __constant);
     }
 
     /** Initializes the iterator to reference the same sequence that
 	@p __x does. @p __constant is true if this is a constant
 	iterator, and false if it is mutable. */
     _GLIBCXX20_CONSTEXPR
-    _Safe_iterator_base(const _Safe_iterator_base& __x, bool __constant)
-    : _Safe_iterator_base()
-    {
-      if (!std::__is_constant_evaluated())
-	this->_M_attach(__x._M_sequence, __constant);
-    }
+    _Safe_iterator_base(const _Safe_iterator_base& __x, bool __constant);
 #pragma GCC diagnostic pop
 
     _GLIBCXX20_CONSTEXPR
@@ -116,6 +113,28 @@ namespace __gnu_debug
 	this->_M_detach();
     }
 
+#if __cplusplus >= 201103L
+    /**
+     * Attach to the same sequence as @p __x taking its place in the list of
+     * iterators.
+     */
+    void
+    _M_inplace_attach(const __gnu_cxx::__scoped_lock& __l,
+		      const _Safe_iterator_base& __x);
+#endif
+
+    /**
+     * Get the sequence this iterator is attached to, or null if singular.
+     */
+    const _Safe_sequence_base*
+    _M_get_sequence() const _GLIBCXX_NOEXCEPT
+    {
+      if (_M_singular())
+	return 0;
+
+      return _M_sequence;
+    }
+
     /** For use in _Safe_iterator. */
     __gnu_cxx::__mutex&
     _M_get_mutex() _GLIBCXX_USE_NOEXCEPT;
@@ -133,8 +152,8 @@ namespace __gnu_debug
     _M_attach_single(const _Safe_sequence_base* __seq,
 		     bool __constant) _GLIBCXX_USE_NOEXCEPT;
 
-    /** Detach the iterator from whatever sequence it is attached to,
-     *	if any.
+    /**
+     * Detach the iterator from whatever sequence it is attached to, if any.
      */
     void
     _M_detach();
@@ -354,6 +373,57 @@ namespace __gnu_debug
     void
     _M_detach_single(_Safe_iterator_base* __it) const _GLIBCXX_USE_NOEXCEPT;
   };
+
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wc++11-extensions"
+  inline _GLIBCXX20_CONSTEXPR
+  _Safe_iterator_base::
+  _Safe_iterator_base(const _Safe_iterator_base& __x, bool __constant)
+  : _Safe_iterator_base()
+  {
+    if (!std::__is_constant_evaluated())
+      {
+	const _Safe_sequence_base* __seq = __x._M_get_sequence();
+	if (__seq)
+	  _M_attach(__seq, __constant);
+	else
+	  {
+	    // Copy __x so that we preserve the value-initialized state of
+	    // __x on the new instance and have it comparable.
+	    _M_sequence = __x._M_sequence;
+	    _M_version = __x._M_version;
+	  }
+      }
+  }
+#pragma GCC diagnostic pop
+
+#if __cplusplus >= 201103L
+  inline void
+  _Safe_iterator_base::
+  _M_inplace_attach(const __gnu_cxx::__scoped_lock&,
+		    const _Safe_iterator_base& __x)
+  {
+    _M_sequence = __x._M_sequence;
+    _M_version = _M_sequence->_M_version;
+
+    if (__x._M_prior)
+      {
+	__x._M_prior->_M_next = this;
+	_M_prior = __x._M_prior;
+      }
+
+    if (__x._M_next)
+      {
+	__x._M_next->_M_prior = this;
+	_M_next = __x._M_next;
+      }
+
+    if (_M_sequence->_M_const_iterators == std::addressof(__x))
+      _M_sequence->_M_const_iterators = this;
+    else if (_M_sequence->_M_iterators == std::addressof(__x))
+      _M_sequence->_M_iterators = this;
+  }
+#endif
 } // namespace __gnu_debug
 
 #endif
diff --git a/libstdc++-v3/include/debug/safe_iterator.h b/libstdc++-v3/include/debug/safe_iterator.h
index 8c049961cca..e2883f862a9 100644
--- a/libstdc++-v3/include/debug/safe_iterator.h
+++ b/libstdc++-v3/include/debug/safe_iterator.h
@@ -133,6 +133,10 @@ namespace __gnu_debug
     {
       typedef std::iterator_traits<_Iterator> _Traits;
 
+      // To access mutable iterator members from the immutable one.
+      template<typename _Ite, typename _Seq, typename _Cat>
+	friend class _Safe_iterator;
+
     protected:
       typedef std::__are_same<typename _Sequence::_Base::const_iterator,
 			      _Iterator> _IsConstant;
@@ -161,7 +165,7 @@ namespace __gnu_debug
       using iterator_concept = std::__detail::__iter_concept<_Iterator>;
 #endif
 
-      /// @post the iterator is singular and unattached
+      /// @post the iterator is singular, value-initialized and unattached
       _GLIBCXX20_CONSTEXPR
       _Safe_iterator() _GLIBCXX_NOEXCEPT : _Iterator() { }
 
@@ -183,50 +187,93 @@ namespace __gnu_debug
        */
       _GLIBCXX20_CONSTEXPR
       _Safe_iterator(const _Safe_iterator& __x) _GLIBCXX_NOEXCEPT
-      : _Iterator(__x), _Safe_iterator_base()
+      : _Iterator(__x), _Safe_iterator_base(__x, _S_constant())
+      { }
+
+    private:
+      /**
+       * @post this reflects @p __x value-initialized state and sequence.
+       */
+      template<typename _Ite>
+	void
+	_M_copy_state(const _Safe_iterator<_Ite, _Sequence, _Category>& __x)
+	_GLIBCXX_NOEXCEPT
 	{
-	if (std::__is_constant_evaluated())
-	  return;
+	  // Copy __x state so that we reflect its value-initialized state.
+	  _M_version = __x._M_version;
+	  base() = __x.base();
 
-	// _GLIBCXX_RESOLVE_LIB_DEFECTS
-	// DR 408. Is vector<reverse_iterator<char*> > forbidden?
-	_GLIBCXX_DEBUG_VERIFY(!__x._M_singular()
-			      || __x._M_value_initialized(),
-			      _M_message(__msg_init_copy_singular)
-			      ._M_iterator(*this, "this")
-			      ._M_iterator(__x, "other"));
-	_M_attach(__x._M_sequence);
+	  // Also copy __x _M_sequence so that assertions can point to original
+	  // sequence. The drawback of doing this is that the destructor will try
+	  // to detach it.
+	  _M_sequence = __x._M_sequence;
 	}
 
 #if __cplusplus >= 201103L
       /**
-       * @brief Move construction.
-       * @post __x is singular and unattached
+       * @post this is value-initialized so that it is copyable/movable.
        */
+      _Iterator
+      _M_move() noexcept
+      {
+	static const _Safe_iterator __value_init_it{};
+
+	_Iterator __it = *this;
+	this->_Safe_iterator_base::operator=(__value_init_it);
+	base() = __value_init_it.base();
+	return __it;
+      }
+
+      template<typename _Ite>
 	_GLIBCXX20_CONSTEXPR
-      _Safe_iterator(_Safe_iterator&& __x) noexcept
-      : _Iterator()
+	_Safe_iterator(_Safe_iterator<_Ite, _Sequence, _Category>&& __x,
+		       bool __x_constant) noexcept
+	: _Iterator(), _Safe_iterator_base()
 	{
 	  if (std::__is_constant_evaluated())
 	    {
 	      base() = __x.base();
 	      return;
 	    }
+	  else
+	    {
+	      const _Safe_sequence_base* __seq = __x._M_get_sequence();
+	      if (!__seq)
+		{
+		  _M_copy_state(__x);
+		  return;
+		}
 
-	_GLIBCXX_DEBUG_VERIFY(!__x._M_singular()
-			      || __x._M_value_initialized(),
-			      _M_message(__msg_init_copy_singular)
-			      ._M_iterator(*this, "this")
-			      ._M_iterator(__x, "other"));
-	const _Safe_sequence_base* __seq = __x._M_sequence;
-	__x._M_detach();
-	std::swap(base(), __x.base());
-	_M_attach(__seq);
+	      _GLIBCXX20_CONSTEXPR_NON_LITERAL_SCOPE_BEGIN {
+		__gnu_cxx::__scoped_lock __l(__x._M_get_mutex());
+		if (_S_constant() == __x_constant)
+		  _M_inplace_attach(__l, __x);
+		else
+		  {
+		    __x._M_detach_single();
+		    _M_attach_single(__seq, _S_constant());
 		  }
+
+		base() = __x._M_move();
+	      } _GLIBCXX20_CONSTEXPR_NON_LITERAL_SCOPE_END
+	    }
+	}
+
+    public:
+      /**
+       * @brief Move construction.
+       * @post __x, if not singular, is singular, value-initialized and
+       * unattached. If already singular, @p __x is left untouched.
+       */
+      _GLIBCXX20_CONSTEXPR
+      _Safe_iterator(_Safe_iterator&& __x) noexcept
+      : _Safe_iterator(std::move(__x), _S_constant())
+      { }
 #endif
 
+    public:
       /**
-       *  @brief Converting constructor from a mutable iterator to a
+       *  @brief Converting copy constructor from a mutable iterator to a
        *  constant iterator.
       */
       template<typename _MutableIterator>
@@ -237,27 +284,29 @@ namespace __gnu_debug
 	      std::__are_same<_MutableIterator, _OtherIterator>::__value,
 			       _Category>::__type>& __x)
 	_GLIBCXX_NOEXCEPT
-	: _Iterator(__x.base())
-	{
-	  if (std::__is_constant_evaluated())
-	    return;
-
-	  // _GLIBCXX_RESOLVE_LIB_DEFECTS
-	  // DR 408. Is vector<reverse_iterator<char*> > forbidden?
-	  _GLIBCXX_DEBUG_VERIFY(!__x._M_singular()
-				|| __x._M_value_initialized(),
-				_M_message(__msg_init_const_singular)
-				._M_iterator(*this, "this")
-				._M_iterator(__x, "other"));
-	  _M_attach(__x._M_sequence);
-	}
+	: _Iterator(__x.base()), _Safe_iterator_base(__x, _S_constant()) { }
 
+#if __cplusplus >= 201103L
       /**
-       * @brief Copy assignment.
+       *  @brief Converting move constructor from a mutable iterator to a
+       *  constant iterator.
       */
+      template<typename _MutableIterator>
+	_GLIBCXX20_CONSTEXPR
+	_Safe_iterator(_Safe_iterator<_MutableIterator, _Sequence,
+		       typename std::__enable_if_t<std::__and_<
+			 std::__bool_constant<_IsConstant::__value>,
+			 std::is_same<_MutableIterator, _OtherIterator>>::value,
+				      _Category>>&& __x) noexcept
+	: _Safe_iterator(std::move(__x), false) { }
+#endif
+
+    private:
+      template<typename _Ite>
 	_GLIBCXX20_CONSTEXPR
 	_Safe_iterator&
-      operator=(const _Safe_iterator& __x) _GLIBCXX_NOEXCEPT
+	_M_copy_assign(const _Safe_iterator<_Ite, _Sequence, _Category>& __x)
+	_GLIBCXX_NOEXCEPT
 	{
 	  if (std::__is_constant_evaluated())
 	    {
@@ -265,38 +314,36 @@ namespace __gnu_debug
 	      return *this;
 	    }
 
-	// _GLIBCXX_RESOLVE_LIB_DEFECTS
-	// DR 408. Is vector<reverse_iterator<char*> > forbidden?
-	_GLIBCXX_DEBUG_VERIFY(!__x._M_singular()
-			      || __x._M_value_initialized(),
-			      _M_message(__msg_copy_singular)
-			      ._M_iterator(*this, "this")
-			      ._M_iterator(__x, "other"));
-
-	if (this->_M_sequence && this->_M_sequence == __x._M_sequence)
 	  _GLIBCXX20_CONSTEXPR_NON_LITERAL_SCOPE_BEGIN {
-	    __gnu_cxx::__scoped_lock __l(this->_M_get_mutex());
+	    const _Safe_sequence_base* __x_seq = __x._M_get_sequence();
+	    const _Safe_sequence_base* __seq = _M_get_sequence();
+	    if (__seq && __seq == __x_seq)
+	      {
+		__gnu_cxx::__scoped_lock __l(_M_get_mutex());
 		base() = __x.base();
-	    _M_version = __x._M_sequence->_M_version;
-	  } _GLIBCXX20_CONSTEXPR_NON_LITERAL_SCOPE_END
+	      }
 	    else
 	      {
 		_M_detach();
+		if (__x_seq)
+		  {
 		    base() = __x.base();
-	    _M_attach(__x._M_sequence);
+		    _M_attach(__x_seq, _S_constant());
+		  }
+		else
+		  _M_copy_state(__x);
 	      }
+	  } _GLIBCXX20_CONSTEXPR_NON_LITERAL_SCOPE_END
 
 	  return *this;
 	}
 
 #if __cplusplus >= 201103L
-      /**
-       * @brief Move assignment.
-       * @post __x is singular and unattached
-       */
+      template<typename _Ite>
 	_GLIBCXX20_CONSTEXPR
 	_Safe_iterator&
-      operator=(_Safe_iterator&& __x) noexcept
+	_M_move_assign(_Safe_iterator<_Ite, _Sequence, _Category>&& __x)
+	  noexcept
 	{
 	  if (std::__is_constant_evaluated())
 	    {
@@ -304,34 +351,78 @@ namespace __gnu_debug
 	      return *this;
 	    }
 
-	_GLIBCXX_DEBUG_VERIFY(!__x._M_singular()
-			      || __x._M_value_initialized(),
-			      _M_message(__msg_copy_singular)
-			      ._M_iterator(*this, "this")
-			      ._M_iterator(__x, "other"));
-
-	if (std::__addressof(__x) == this)
+	  _Safe_iterator_base& __x_base = __x;
+	  _Safe_iterator_base& __this_base = *this;
+	  if (std::addressof(__x_base) == std::addressof(__this_base))
 	    return *this;
 
-	if (this->_M_sequence && this->_M_sequence == __x._M_sequence)
 	  _GLIBCXX20_CONSTEXPR_NON_LITERAL_SCOPE_BEGIN {
-	    __gnu_cxx::__scoped_lock __l(this->_M_get_mutex());
-	    base() = __x.base();
-	    _M_version = __x._M_sequence->_M_version;
-	  } _GLIBCXX20_CONSTEXPR_NON_LITERAL_SCOPE_END
+	    const _Safe_sequence_base* __x_seq = __x._M_get_sequence();
+	    const _Safe_sequence_base* __seq = _M_get_sequence();
+	    if (__seq && __seq == __x_seq)
+	      {
+		__gnu_cxx::__scoped_lock __l(_M_get_mutex());
+		__x._M_detach_single();
+		base() = __x._M_move();
+	      }
 	    else
 	      {
 		_M_detach();
-	    base() = __x.base();
-	    _M_attach(__x._M_sequence);
-	  }
 
+		if (__x_seq)
+		  {
 		    __x._M_detach();
-	__x.base() = _Iterator();
+		    base() = __x._M_move();
+		    _M_attach(__x_seq, _S_constant());
+		  }
+		else
+		  _M_copy_state(__x);
+	      }
+	  } _GLIBCXX20_CONSTEXPR_NON_LITERAL_SCOPE_END
+
 	  return *this;
 	}
 #endif
 
+    public:
+      /**
+       * @brief Copy assignment.
+       */
+      _GLIBCXX20_CONSTEXPR
+      _Safe_iterator&
+      operator=(const _Safe_iterator& __x) _GLIBCXX_NOEXCEPT
+      { return _M_copy_assign(__x); }
+
+      template<typename _MutableIterator>
+	_GLIBCXX20_CONSTEXPR
+	_Safe_iterator&
+	operator=(const _Safe_iterator<_MutableIterator, _Sequence,
+		  typename __gnu_cxx::__enable_if<_IsConstant::__value &&
+		    std::__are_same<_MutableIterator, _OtherIterator>::__value,
+				_Category>::__type>& __x) _GLIBCXX_NOEXCEPT
+	{ return _M_copy_assign(__x); }
+
+#if __cplusplus >= 201103L
+      /**
+       * @brief Move assignment.
+       * @post __x is singular and unattached
+       */
+      _GLIBCXX20_CONSTEXPR
+      _Safe_iterator&
+      operator=(_Safe_iterator&& __x) noexcept
+      { return _M_move_assign(std::move(__x)); }
+
+      template<typename _MutableIterator>
+	_GLIBCXX20_CONSTEXPR
+	_Safe_iterator&
+	operator=(_Safe_iterator<_MutableIterator, _Sequence,
+		       typename std::__enable_if_t<std::__and_<
+			 std::__bool_constant<_IsConstant::__value>,
+			 std::is_same<_MutableIterator, _OtherIterator>>::value,
+				 _Category>>&& __x) noexcept
+	{ return _M_move_assign(std::move(__x)); }
+#endif
+
       /**
        *  @brief Iterator dereference.
        *  @pre iterator is dereferenceable
@@ -437,16 +528,6 @@ namespace __gnu_debug
       _GLIBCXX20_CONSTEXPR
       operator _Iterator() const _GLIBCXX_NOEXCEPT { return *this; }
 
-      /** Attach iterator to the given sequence. */
-      void
-      _M_attach(const _Safe_sequence_base* __seq)
-      { _Safe_iterator_base::_M_attach(__seq, _S_constant()); }
-
-      /** Likewise, but not thread-safe. */
-      void
-      _M_attach_single(const _Safe_sequence_base* __seq)
-      { _Safe_iterator_base::_M_attach_single(__seq, _S_constant()); }
-
       /// Is the iterator dereferenceable?
       bool
       _M_dereferenceable() const
@@ -490,16 +571,19 @@ namespace __gnu_debug
 		     std::pair<difference_type, _Distance_precision>& __dist,
 		     bool __check_dereferenceable = true) const;
 
-      // The sequence this iterator references.
+      // The sequence this iterator references, if not singular.
+      _GLIBCXX20_CONSTEXPR
       typename __gnu_cxx::__conditional_type<
 	_IsConstant::__value, const _Sequence*, _Sequence*>::__type
-      _M_get_sequence() const
+      _M_get_sequence() const _GLIBCXX_NOEXCEPT
       {
+	const _Safe_sequence_base* __seq
+	  = _Safe_iterator_base::_M_get_sequence();
+
 	// Looks like not const-correct, but if _IsConstant the constness
 	// is restored when returning the sequence pointer and if not
 	// _IsConstant we are allowed to remove constness.
-	return static_cast<_Sequence*>
-	  (const_cast<_Safe_sequence_base*>(_M_sequence));
+	return static_cast<_Sequence*>(const_cast<_Safe_sequence_base*>(__seq));
       }
 
       // Get distance to __rhs.
@@ -609,6 +693,8 @@ namespace __gnu_debug
 
       typedef typename _Safe_base::_Unchecked _Unchecked;
 
+      typedef typename _Safe_base::_IsConstant _IsConstant;
+
       _GLIBCXX20_CONSTEXPR
       _Safe_iterator(const _Safe_iterator& __x,
 		     _Unchecked __unchecked) _GLIBCXX_NOEXCEPT
@@ -616,9 +702,21 @@ namespace __gnu_debug
       { }
 
     public:
+
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wc++11-extensions"
       /// @post the iterator is singular and unattached
-      _GLIBCXX20_CONSTEXPR
-      _Safe_iterator() _GLIBCXX_NOEXCEPT { }
+      _Safe_iterator() = default;
+
+      /**
+       * @brief Copy construction.
+       */
+      _Safe_iterator(const _Safe_iterator&) = default;
+
+      /** @brief Copy assignment. */
+      _Safe_iterator&
+      operator=(const _Safe_iterator&) = default;
+#pragma GCC diagnostic pop
 
       /**
        * @brief Safe iterator construction from an unsafe iterator and
@@ -633,49 +731,68 @@ namespace __gnu_debug
       : _Safe_base(__i, __seq)
       { }
 
-      /**
-       * @brief Copy construction.
-       */
-      _GLIBCXX20_CONSTEXPR
-      _Safe_iterator(const _Safe_iterator& __x) _GLIBCXX_NOEXCEPT
-      : _Safe_base(__x)
-      { }
-
 #if __cplusplus >= 201103L
       /** @brief Move construction. */
-      _GLIBCXX20_CONSTEXPR
       _Safe_iterator(_Safe_iterator&&) = default;
 #endif
 
       /**
-       *  @brief Converting constructor from a mutable iterator to a
+       *  @brief Converting copy constructor from a mutable iterator to a
        *  constant iterator.
       */
       template<typename _MutableIterator>
 	_GLIBCXX20_CONSTEXPR
 	_Safe_iterator(
 	  const _Safe_iterator<_MutableIterator, _Sequence,
-	    typename __gnu_cxx::__enable_if<_Safe_base::_IsConstant::__value &&
+	    typename __gnu_cxx::__enable_if<_IsConstant::__value &&
 	      std::__are_same<_MutableIterator, _OtherIterator>::__value,
 			       std::bidirectional_iterator_tag>::__type>& __x)
 	_GLIBCXX_NOEXCEPT
-	: _Safe_base(__x)
-        { }
+	: _Safe_base(__x) { }
 
 #if __cplusplus >= 201103L
-      /** @brief Copy assignment. */
+      /**
+       *  @brief Converting move constructor from a mutable iterator to a
+       *  constant iterator.
+      */
+      template<typename _MutableIterator>
+	_GLIBCXX20_CONSTEXPR
+	_Safe_iterator(_Safe_iterator<_MutableIterator, _Sequence,
+	  typename std::__enable_if_t<std::__and_<
+	    std::__bool_constant<_IsConstant::__value>,
+	    std::is_same<_MutableIterator, _OtherIterator>>::value,
+		       std::bidirectional_iterator_tag>>&& __x) noexcept
+	: _Safe_base(std::move(__x)) { }
+#endif
+
+      template<typename _MutableIterator>
+	_GLIBCXX20_CONSTEXPR
 	_Safe_iterator&
-      operator=(const _Safe_iterator&) = default;
+	operator=(const _Safe_iterator<_MutableIterator, _Sequence,
+		  typename __gnu_cxx::__enable_if<_IsConstant::__value &&
+		    std::__are_same<_MutableIterator, _OtherIterator>::__value,
+		  std::bidirectional_iterator_tag>::__type>& __x)
+	_GLIBCXX_NOEXCEPT
+	{
+	  _Safe_base::operator=(__x);
+	  return *this;
+	}
 
+#if __cplusplus >= 201103L
       /** @brief Move assignment. */
       _Safe_iterator&
       operator=(_Safe_iterator&&) = default;
-#else
-      /** @brief Copy assignment. */
+
+      template<typename _MutableIterator>
+	_GLIBCXX20_CONSTEXPR
 	_Safe_iterator&
-      operator=(const _Safe_iterator& __x)
+	operator=(_Safe_iterator<_MutableIterator, _Sequence,
+	  typename std::__enable_if_t<std::__and_<
+	    std::__bool_constant<_IsConstant::__value>,
+	    std::is_same<_MutableIterator, _OtherIterator>>::value,
+		  std::bidirectional_iterator_tag>>&& __x) noexcept
 	{
-	_Safe_base::operator=(__x);
+	  _Safe_base::operator=(std::move(__x));
 	  return *this;
 	}
 #endif
@@ -771,6 +888,8 @@ namespace __gnu_debug
 
       typedef typename _Safe_base::_Unchecked _Unchecked;
 
+      typedef typename _Safe_base::_IsConstant _IsConstant;
+
       _GLIBCXX20_CONSTEXPR
       _Safe_iterator(const _Safe_iterator& __x,
 		     _Unchecked __unchecked) _GLIBCXX_NOEXCEPT
@@ -781,9 +900,20 @@ namespace __gnu_debug
       typedef typename _Safe_base::difference_type	difference_type;
       typedef typename _Safe_base::reference		reference;
 
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wc++11-extensions"
       /// @post the iterator is singular and unattached
-      _GLIBCXX20_CONSTEXPR
-      _Safe_iterator() _GLIBCXX_NOEXCEPT { }
+      _Safe_iterator() = default;
+
+      /**
+       * @brief Copy construction.
+       */
+      _Safe_iterator(const _Safe_iterator& __x) = default;
+
+      /** @brief Copy assignment. */
+      _Safe_iterator&
+      operator=(const _Safe_iterator&) = default;
+#pragma GCC diagnostic pop
 
       /**
        * @brief Safe iterator construction from an unsafe iterator and
@@ -798,28 +928,20 @@ namespace __gnu_debug
       : _Safe_base(__i, __seq)
       { }
 
-      /**
-       * @brief Copy construction.
-       */
-      _GLIBCXX20_CONSTEXPR
-      _Safe_iterator(const _Safe_iterator& __x) _GLIBCXX_NOEXCEPT
-      : _Safe_base(__x)
-      { }
-
 #if __cplusplus >= 201103L
       /** @brief Move construction. */
       _Safe_iterator(_Safe_iterator&&) = default;
 #endif
 
       /**
-       *  @brief Converting constructor from a mutable iterator to a
+       *  @brief Converting copy constructor from a mutable iterator to a
        *  constant iterator.
       */
       template<typename _MutableIterator>
 	_GLIBCXX20_CONSTEXPR
 	_Safe_iterator(
 	  const _Safe_iterator<_MutableIterator, _Sequence,
-	    typename __gnu_cxx::__enable_if<_Safe_base::_IsConstant::__value &&
+	    typename __gnu_cxx::__enable_if<_IsConstant::__value &&
 	      std::__are_same<_MutableIterator, _OtherIterator>::__value,
 			       std::random_access_iterator_tag>::__type>& __x)
 	_GLIBCXX_NOEXCEPT
@@ -827,19 +949,49 @@ namespace __gnu_debug
 	{ }
 
 #if __cplusplus >= 201103L
-      /** @brief Copy assignment. */
+      /**
+       *  @brief Converting move constructor from a mutable iterator to a
+       *  constant iterator.
+      */
+      template<typename _MutableIterator>
+	_GLIBCXX20_CONSTEXPR
+	_Safe_iterator(_Safe_iterator<_MutableIterator, _Sequence,
+	  typename std::__enable_if_t<std::__and_<
+	    std::__bool_constant<_IsConstant::__value>,
+	    std::is_same<_MutableIterator, _OtherIterator>>::value,
+			std::random_access_iterator_tag>>&& __x) noexcept
+	: _Safe_base(std::move(__x))
+	{ }
+#endif
+
+      template<typename _MutableIterator>
+	_GLIBCXX20_CONSTEXPR
 	_Safe_iterator&
-      operator=(const _Safe_iterator&) = default;
+	operator=(const _Safe_iterator<_MutableIterator, _Sequence,
+		  typename __gnu_cxx::__enable_if<_IsConstant::__value &&
+		    std::__are_same<_MutableIterator, _OtherIterator>::__value,
+		  std::random_access_iterator_tag>::__type>& __x)
+	_GLIBCXX_NOEXCEPT
+	{
+	  _Safe_base::operator=(__x);
+	  return *this;
+	}
 
+#if __cplusplus >= 201103L
       /** @brief Move assignment. */
       _Safe_iterator&
       operator=(_Safe_iterator&&) = default;
-#else
-      /** @brief Copy assignment. */
+
+      template<typename _MutableIterator>
+	_GLIBCXX20_CONSTEXPR
 	_Safe_iterator&
-      operator=(const _Safe_iterator& __x)
+	operator=(_Safe_iterator<_MutableIterator, _Sequence,
+	  typename std::__enable_if_t<std::__and_<
+	    std::__bool_constant<_IsConstant::__value>,
+	    std::is_same<_MutableIterator, _OtherIterator>>::value,
+		  std::random_access_iterator_tag>>&& __x) noexcept
 	{
-	_Safe_base::operator=(__x);
+	  _Safe_base::operator=(std::move(__x));
 	  return *this;
 	}
 #endif
diff --git a/libstdc++-v3/src/c++11/debug.cc b/libstdc++-v3/src/c++11/debug.cc
index 9a36bdfabb9..127cf7312d9 100644
--- a/libstdc++-v3/src/c++11/debug.cc
+++ b/libstdc++-v3/src/c++11/debug.cc
@@ -478,8 +478,6 @@ namespace __gnu_debug
 	_M_version = _M_sequence->_M_version;
 	_M_sequence->_M_attach(this, __constant);
       }
-    else
-      _M_version = 0;
   }
 
   void
@@ -495,8 +493,6 @@ namespace __gnu_debug
 	_M_version = _M_sequence->_M_version;
 	_M_sequence->_M_attach_single(this, __constant);
       }
-    else
-      _M_version = 0;
   }
 
   void
diff --git a/libstdc++-v3/testsuite/24_iterators/debug/safe_iterator.cc b/libstdc++-v3/testsuite/24_iterators/debug/safe_iterator.cc
new file mode 100644
index 00000000000..2b8bb289e11
--- /dev/null
+++ b/libstdc++-v3/testsuite/24_iterators/debug/safe_iterator.cc
@@ -0,0 +1,138 @@
+// { dg-options "-D_GLIBCXX_DEBUG" }
+// { dg-do run { target c++11 } }
+
+#include <vector>
+#include <algorithm>
+
+#include <testsuite_hooks.h>
+
+static void
+test_swap()
+{
+  std::vector<int> v{1};
+  auto i = v.begin();
+  std::swap(i, i);
+  VERIFY( *i == 1 );
+}
+
+static void
+test_state()
+{
+  std::vector<int> v{1};
+  auto i = v.begin();
+  VERIFY( *i == 1 );
+
+  v.clear();
+  VERIFY( i._M_singular() );
+  VERIFY( i._M_sequence != nullptr );
+  VERIFY( i._M_version != 0 );
+
+  auto j = i;
+  VERIFY( j._M_singular() );
+  VERIFY( i._M_sequence == j._M_sequence );
+  VERIFY( i._M_version == j._M_version );
+
+  j = i;
+  VERIFY( j._M_singular() );
+  VERIFY( i._M_sequence == j._M_sequence );
+  VERIFY( i._M_version == j._M_version );
+
+  typename std::vector<int>::const_iterator ci = i;
+  VERIFY( ci._M_singular() );
+  VERIFY( ci._M_sequence == j._M_sequence );
+  VERIFY( ci._M_version == j._M_version );
+
+  ci = i;
+  VERIFY( ci._M_singular() );
+  VERIFY( ci._M_sequence == j._M_sequence );
+  VERIFY( ci._M_version == j._M_version );
+}
+
+static void
+test_copy()
+{
+  std::vector<int> v{1};
+  auto i = v.begin();
+  auto j = std::move(i); // i enters moved-from state via move constructor
+  VERIFY( *j == 1 );
+  j = i;      // copy assignment using moved-from iterator
+  VERIFY( j == i );
+  auto k = i; // copy construction using moved-from iterator
+  VERIFY( k == i );
+  k = i;      // copy assignment using moved-from iterator
+  VERIFY( k == i );
+
+  i = v.begin();
+  j = std::move(i); // i enters moved-from state via move assignment
+  VERIFY( *j == 1 );
+  j = i;      // copy assignment using moved-from iterator
+  VERIFY( j == i );
+  auto l = i; // copy construction using moved-from iterator
+  VERIFY( l == i );
+  l = i;      // copy assignment using moved-from iterator
+  VERIFY( l == i );
+
+  i = v.begin();
+  j = v.begin();
+  j = std::move(i); // i enters moved-from state via move constructor
+  VERIFY( *j == 1 );
+}
+
+static void
+test_move()
+{
+  std::vector<int> v{1};
+  auto i = v.begin();
+  auto j = std::move(i); // i enters moved-from state via move constructor
+  VERIFY( *j == 1 );
+  j = std::move(i);      // move assignment using moved-from iterator
+  VERIFY( j == i );
+  auto k = std::move(i); // move construction using moved-from iterator
+  VERIFY( k == i );
+  k = std::move(i);      // move assignment using moved-from iterator
+  VERIFY( k == i );
+
+  i = v.begin();
+  j = std::move(i);      // i enters moved-from state via move assignment
+  VERIFY( *j == 1 );
+  j = std::move(i);      // move assignment using moved-from iterator
+  VERIFY( j == i );
+  auto l = std::move(i); // move construction using moved-from iterator
+  VERIFY( l == i );
+  l = std::move(i);      // move assignment using moved-from iterator
+  VERIFY( l == i );
+}
+
+static void
+test_conversion()
+{
+  std::vector<int> v{1};
+  auto i = v.begin();
+  typename std::vector<int>::const_iterator j = std::move(i); // i enters moved-from state via move constructor
+  VERIFY( *j == 1 );
+  j = std::move(i);      // move assignment using moved-from iterator
+  VERIFY( j == i );
+  typename std::vector<int>::const_iterator k = std::move(i); // move construction using moved-from iterator
+  VERIFY( k == i );
+  k = std::move(i);      // move assignment using moved-from iterator
+  VERIFY( k == i );
+
+  i = v.begin();
+  j = std::move(i);      // i enters moved-from state via move assignment
+  VERIFY( *j == 1 );
+  j = std::move(i);      // move assignment using moved-from iterator
+  VERIFY( j == i );
+  typename std::vector<int>::const_iterator l = std::move(i); // move construction using moved-from iterator
+  VERIFY( l == i );
+  l = std::move(i);      // move assignment using moved-from iterator
+  VERIFY( l == i );
+}
+
+int main()
+{
+  test_swap();
+  test_state();
+  test_copy();
+  test_move();
+  test_conversion();
+}


More information about the Libstdc++ mailing list