From 9fd7e21ef78952967e94785180164aaf2821a892 Mon Sep 17 00:00:00 2001 From: Li Zhiyuan Date: Wed, 3 Jan 2024 14:22:15 +0800 Subject: [PATCH] Fix scoped_refptr leave ptr_ uninit when move construct by nullptr (#2491) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Fix scoped_refptr leave ptr_ uninit when move construct by nullptr --------- Co-authored-by: 扬宁 --- src/butil/memory/ref_counted.h | 14 +++++--------- test/ref_counted_unittest.cc | 13 +++++++++++++ 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/src/butil/memory/ref_counted.h b/src/butil/memory/ref_counted.h index 8fbb5d0ddd..fb8bc72d0a 100644 --- a/src/butil/memory/ref_counted.h +++ b/src/butil/memory/ref_counted.h @@ -286,20 +286,16 @@ class scoped_refptr { } scoped_refptr(scoped_refptr&& r) noexcept { - if (r.ptr_){ - ptr_ = r.ptr_; - r.ptr_ = nullptr; - } + ptr_ = r.ptr_; + r.ptr_ = nullptr; } template scoped_refptr(scoped_refptr&& r) noexcept { - if (r.ptr_){ - ptr_ = r.ptr_; - r.ptr_ = nullptr; - } + ptr_ = r.ptr_; + r.ptr_ = nullptr; } - + ~scoped_refptr() { if (ptr_) ptr_->Release(); diff --git a/test/ref_counted_unittest.cc b/test/ref_counted_unittest.cc index 8de760026e..7415ba3e84 100644 --- a/test/ref_counted_unittest.cc +++ b/test/ref_counted_unittest.cc @@ -82,3 +82,16 @@ TEST(RefCountedUnitTest, ScopedRefPtrBooleanOperations) { EXPECT_NE(raw_p, p2); EXPECT_EQ(p1, p2); } + +TEST(RefCountedUnitTest, ScopedRefPtrMoveCtor) +{ + scoped_refptr p1 = new SelfAssign; + EXPECT_TRUE(p1); + + scoped_refptr p2(std::move(p1)); + EXPECT_TRUE(p2); + EXPECT_FALSE(p1); + + scoped_refptr p3(std::move(p1)); + EXPECT_FALSE(p3); +}