Add StrongPointer::release()
Useful when dealing with raw pointers in unavoidable places. Avoids an awkward (and "slow") dance of mySp->incStrong(0); mySp->get(); ~mySp; Test: make && atest --host libutils_binder_test Change-Id: Ib8d46150592725cc256779bccfed19a16dce78b2
This commit is contained in:
parent
ced62e53ed
commit
e01550bbb6
2 changed files with 23 additions and 0 deletions
|
@ -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!";
|
||||
}
|
||||
|
|
|
@ -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; }
|
||||
|
|
Loading…
Reference in a new issue