Skip to content

Commit

Permalink
Fix scoped_refptr leave ptr_ uninit when move construct by nullptr (#…
Browse files Browse the repository at this point in the history
…2491)

* Fix scoped_refptr leave ptr_ uninit when move construct by nullptr

---------

Co-authored-by: 扬宁 <yangning.lzy@alibaba-inc.com>
  • Loading branch information
lengmoXXL and 扬宁 authored Jan 3, 2024
1 parent 023fa14 commit 9fd7e21
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 9 deletions.
14 changes: 5 additions & 9 deletions src/butil/memory/ref_counted.h
Original file line number Diff line number Diff line change
Expand Up @@ -286,20 +286,16 @@ class scoped_refptr {
}

scoped_refptr(scoped_refptr<T>&& r) noexcept {
if (r.ptr_){
ptr_ = r.ptr_;
r.ptr_ = nullptr;
}
ptr_ = r.ptr_;
r.ptr_ = nullptr;
}

template <typename U>
scoped_refptr(scoped_refptr<U>&& r) noexcept {
if (r.ptr_){
ptr_ = r.ptr_;
r.ptr_ = nullptr;
}
ptr_ = r.ptr_;
r.ptr_ = nullptr;
}

~scoped_refptr() {
if (ptr_)
ptr_->Release();
Expand Down
13 changes: 13 additions & 0 deletions test/ref_counted_unittest.cc
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,16 @@ TEST(RefCountedUnitTest, ScopedRefPtrBooleanOperations) {
EXPECT_NE(raw_p, p2);
EXPECT_EQ(p1, p2);
}

TEST(RefCountedUnitTest, ScopedRefPtrMoveCtor)
{
scoped_refptr<SelfAssign> p1 = new SelfAssign;
EXPECT_TRUE(p1);

scoped_refptr<SelfAssign> p2(std::move(p1));
EXPECT_TRUE(p2);
EXPECT_FALSE(p1);

scoped_refptr<SelfAssign> p3(std::move(p1));
EXPECT_FALSE(p3);
}

0 comments on commit 9fd7e21

Please sign in to comment.