Merge "Add StrongPointer::release()" into main

This commit is contained in:
Treehugger Robot 2023-11-20 18:27:15 +00:00 committed by Gerrit Code Review
commit 558fd9ab7a
2 changed files with 23 additions and 0 deletions

View file

@ -106,3 +106,17 @@ TYPED_TEST(StrongPointer, AssertStrongRefExists) {
EXPECT_DEATH(sp<TypeParam>::fromExisting(foo), "");
delete foo;
}
TYPED_TEST(StrongPointer, release) {
bool isDeleted = false;
TypeParam* foo = nullptr;
{
sp<TypeParam> sp1 = sp<TypeParam>::make(&isDeleted);
ASSERT_EQ(1, sp1->getStrongCount());
foo = sp1.release();
}
ASSERT_FALSE(isDeleted) << "release failed, deleted anyway when sp left scope";
ASSERT_EQ(1, foo->getStrongCount()) << "release mismanaged refcount";
foo->decStrong(nullptr);
ASSERT_TRUE(isDeleted) << "foo was leaked!";
}

View file

@ -98,6 +98,15 @@ public:
void clear();
// Releases the ownership of the object managed by this instance of sp, if any.
// The caller is now responsible for managing it. That is, the caller must ensure
// decStrong() is called when the pointer is no longer used.
[[nodiscard]] inline T* release() noexcept {
auto ret = m_ptr;
m_ptr = nullptr;
return ret;
}
// Accessors
inline T& operator* () const { return *m_ptr; }