]> git.ipfire.org Git - thirdparty/gcc.git/commitdiff
libstdc++: Fix self-move for std::weak_ptr [PR108118]
authorJonathan Wakely <jwakely@redhat.com>
Thu, 15 Dec 2022 09:52:48 +0000 (09:52 +0000)
committerJonathan Wakely <jwakely@redhat.com>
Tue, 16 May 2023 10:15:01 +0000 (11:15 +0100)
I think an alternative fix would be something like:

  _M_ptr = std::exchange(rhs._M_ptr, nullptr);
  _M_refcount = std::move(rhs._M_refcount);

The standard's move-and-swap implementation generates smaller code at
all levels except -O0 and -Og, so it seems simplest to just do what the
standard says.

libstdc++-v3/ChangeLog:

PR libstdc++/108118
* include/bits/shared_ptr_base.h (weak_ptr::operator=):
Implement as move-and-swap exactly as specified in the standard.
* testsuite/20_util/weak_ptr/cons/self_move.cc: New test.

(cherry picked from commit 92eb0adc14a5f84acce7e5bc780b81b1544b24aa)

libstdc++-v3/include/bits/shared_ptr_base.h
libstdc++-v3/testsuite/20_util/weak_ptr/cons/self_move.cc [new file with mode: 0644]

index eb9ad23ba1e3d37a9230bfad048c0296066c9424..611680692fda68dc0bddd49cd7e6331b43d5648f 100644 (file)
@@ -1666,9 +1666,7 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
       __weak_ptr&
       operator=(__weak_ptr&& __r) noexcept
       {
-       _M_ptr = __r._M_ptr;
-       _M_refcount = std::move(__r._M_refcount);
-       __r._M_ptr = nullptr;
+       __weak_ptr(std::move(__r)).swap(*this);
        return *this;
       }
 
diff --git a/libstdc++-v3/testsuite/20_util/weak_ptr/cons/self_move.cc b/libstdc++-v3/testsuite/20_util/weak_ptr/cons/self_move.cc
new file mode 100644 (file)
index 0000000..c890d2b
--- /dev/null
@@ -0,0 +1,19 @@
+// { dg-do run { target c++11 } }
+
+#include <memory>
+#include <testsuite_hooks.h>
+
+void
+test_self_move()
+{
+  std::shared_ptr<int> sp(new int(66));
+  std::weak_ptr<int> wp(sp);
+  wp = std::move(wp); // PR libstdc++/108118
+  std::shared_ptr<int> sp2(wp);
+  VERIFY(sp2 == sp);
+}
+
+int main()
+{
+  test_self_move();
+}