Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit e01550bb authored by John Reck's avatar John Reck
Browse files

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
parent ced62e53
Loading
Loading
Loading
Loading
+14 −0
Original line number Diff line number Diff line
@@ -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!";
}
+9 −0
Original line number Diff line number Diff line
@@ -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; }