Android智能指针SP WP

1.概述

Android的C++部分代码中有大量的sp/wp存在,意思是strong pointer和weak pointer,看字面意思就是指针相关的东西。C++是通过new和delete进行内存的分配和释放的,但是有时候开发者会忘记使用delete导致内存泄露,所以Android中就创建了sp/wp等,用于避免内存泄露和提高开发效率。
强指针通过引用计数来记录有多少使用者在使用一个对象,如果所有使用者都放弃了对该对象的引用,则该对象将被自动销毁。弱指针仅仅记录该对象的地址,不能通过弱指针来访问该对象,也就是说不能通过弱智真来调用对象的成员函数或访问对象的成员变量。要想访问弱指针所指向的对象,需首先通过wp所提供的promote()方法将弱指针升级为强指针。弱指针所指向的对象是有可能在其它地方被销毁的,如果对象已经被销毁,wp的promote()方法将返回空指针,这样就能避免出现地址访问错的情况
在这里插入图片描述

2. sp

system\core\libutils\include\utils\StrongPointer.h
system\core\libutils\StrongPointer.cpp

template<typename T>
sp<T>::sp(T* other)
        : m_ptr(other) {
    if (other) {
        check_not_on_stack(other);
        other->incStrong(this);
    }
}
template <typename T>
template <typename U>
sp<T>::sp(U* other) : m_ptr(other) {
    if (other) {
        check_not_on_stack(other);
        (static_cast<T*>(other))->incStrong(this);
    }
}
template<typename T>
sp<T>::sp(const sp<T>& other)
        : m_ptr(other.m_ptr) {
    if (m_ptr)
        m_ptr->incStrong(this);
}
template <typename T>
sp<T>::sp(sp<T>&& other) noexcept : m_ptr(other.m_ptr) {
    other.m_ptr = nullptr;
}
template<typename T> template<typename U>
sp<T>::sp(const sp<U>& other)
        : m_ptr(other.m_ptr) {
    if (m_ptr)
        m_ptr->incStrong(this);
}
template<typename T> template<typename U>
sp<T>::sp(sp<U>&& other)
        : m_ptr(other.m_ptr) {
    other.m_ptr = nullptr;
}
初始化sp中的指针m_ptr
m_ptr调用incStrong函数,进行计数加1
template <typename T>
template <typename... Args>
sp<T> sp<T>::make(Args&&... args) {
    T* t = new T(std::forward<Args>(args)...);
    sp<T> result;
    result.m_ptr = t;
    t->incStrong(t);  // bypass check_not_on_stack for heap allocation
    return result;
}
sp实际就是一个引用,不会单独的申请内存,对引用对象的初始化是在make中
初始化m_ptr指针
引用计数加一

3.示例

在Android中,大多数类的最上层基类都是RefBase类。我们举个简单的例子,然后顺着这个例子来分析RefBase、sp和wp四种不同的应用,并介绍其实现

3.1 只有sp指针,没有wp指针的应用

class A : public RefBase
{
}

上面定义一个类A,继承与RefBase,下面我们首先来看RefBases的构造函数:

RefBase::RefBase()
    : mRefs(new weakref_impl(this))
{
}
 
    explicit weakref_impl(RefBase* base)
        : mStrong(INITIAL_STRONG_VALUE)
        , mWeak(0)
        , mBase(base)
        , mFlags(OBJECT_LIFETIME_STRONG)
    {
    }

explicit关键字通常用来将构造函数标记为显式类型转换,即在创建对象的时候不能进行隐式类型转换。
在RefBase中,首先构造weakref_impl对象,在weakref_impl对mStong和mWeak进行强弱引用计数赋初始值,INITIAL_STRONG_VALUE是0X10000000,这里不直接赋初始值为0,是方便我们区分,0到底是初始化的值,还是在sp释放后再变为0,方便做不同的处理。

{

    sp<A> spA(new A);

}

首先来看sp的构造函数:

template<typename T>
sp<T>::sp(T* other)
        : m_ptr(other) {
    if (other)
        other->incStrong(this);
}

首先将实际的A对象的指针赋给m_ptr,然后调用A对象的incStrong方法,由上面的类图关系,我们知道这里会调用RefBase的incStrong方法:

void RefBase::incStrong(const void* id) const
{
    weakref_impl* const refs = mRefs;
    refs->incWeak(id);

    refs->addStrongRef(id);
    const int32_t c = refs->mStrong.fetch_add(1, std::memory_order_relaxed);
    ALOG_ASSERT(c > 0, "incStrong() called on %p after last strong ref", refs);
#if PRINT_REFS
    ALOGD("incStrong of %p from %p: cnt=%d\n", this, id, c);
#endif
    if (c != INITIAL_STRONG_VALUE)  {
        return;
    }

    int32_t old __unused = refs->mStrong.fetch_sub(INITIAL_STRONG_VALUE, std::memory_order_relaxed);
    // A decStrong() must still happen after us.
    ALOG_ASSERT(old > INITIAL_STRONG_VALUE, "0x%x too small", old);
    refs->mBase->onFirstRef();
}
	

这里首先调用weakref_impl的incWeak方法来增加弱指针引用数;addStrongRef增加强指针引用数;fetch_add是一个原子操作,增加refs->mStrong的强指针引用数,并返回原值;如果是第一次引用改对象,则还会调用A对象的onFirstRef方法。首先来看incWeak的实现

void RefBase::weakref_type::incWeak(const void* id)
{
    weakref_impl* const impl = static_cast<weakref_impl*>(this);
    impl->addWeakRef(id);
    const int32_t c = android_atomic_inc(&impl->mWeak);
    ALOG_ASSERT(c >= 0, "incWeak called on %p after last weak ref", this);
}

这里还是调用android_atomic_inc去增加weakref_impl的mWeak计数。经过构造函数,mStong和mWeak的计数都变成了1。当spA对象退出作用域以后,就会调用其析构函数来释放这个对象:

template<typename T>
sp<T>::~sp() {
    if (m_ptr)
        m_ptr->decStrong(this);
}
 
void RefBase::decStrong(const void* id) const
{
    weakref_impl* const refs = mRefs;
    refs->removeStrongRef(id);
    const int32_t c = android_atomic_dec(&refs->mStrong);
 
    ALOG_ASSERT(c >= 1, "decStrong() called on %p too many times", refs);
    if (c == 1) {
        refs->mBase->onLastStrongRef(id);
        if ((refs->mFlags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
            delete this;
        }
    }
    refs->decWeak(id);
}

sp对象的析构函数调用RefBase的decStrong来减少强弱引用指针计数。weakref_impl的removeStrongRef用于debug版本;调用android_atomic_dec减少mStrong计数并返回原值,如果mStrong之前为1了,这是再减少,说明已经没有其它sp指针引用了,这时候首先调用A对象的onLastStrongRef方法,如果Flag设定的是当前对象的生命周期由sp指针决定(这也是default的设定),则释放掉A对象;然后调用weakref_impl的decWeak去减少弱引用指针计数:

void RefBase::weakref_type::decWeak(const void* id)
{
    weakref_impl* const impl = static_cast<weakref_impl*>(this);
    impl->removeWeakRef(id);
    const int32_t c = android_atomic_dec(&impl->mWeak);
    ALOG_ASSERT(c >= 1, "decWeak called on %p too many times", this);
    if (c != 1) return;
 
    if ((impl->mFlags&OBJECT_LIFETIME_WEAK) == OBJECT_LIFETIME_STRONG) {
        if (impl->mStrong == INITIAL_STRONG_VALUE) {
            delete impl->mBase;
        } else {
            delete impl;
        }
    } else {
        impl->mBase->onLastWeakRef(id);
        if ((impl->mFlags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_WEAK) {
            delete impl->mBase;
        }
    }
}

weakref_impl的removeWeakRef方法也是用于debug版本;然后调用android_atomic_dec去减少mWeak计数,如果mWeak之前不等于1,表示还有其它的wp引用,这里就直接返回。如果这里的mWeak等于1,说明已经没有其它sp和wp的引用了,所以这里要去释放A对象和weakref_impl对象。
来看判断是否释放的逻辑,如果Flag设定当前对象的生命周期由sp指针决定,并且之前没有初始化过任何sp对象,则直接删除A对象;如果之前由初始化过sp对象,则删除weakref_impl本身,A对象会在RefBase的decStrong中被释放。如果Flag设定当前对象的生命周期由wp指针决定,则首先调用A对象的onLastWeakRef方法,然后删除对象A。在删除对象A的时候,都会调用RefBase的析构函数,我们再来分析RefBase的系统函数:

RefBase::~RefBase()
{
    if (mRefs->mStrong == INITIAL_STRONG_VALUE) {
        delete mRefs;
    } else {
        if ((mRefs->mFlags & OBJECT_LIFETIME_MASK) != OBJECT_LIFETIME_STRONG) {
            if (mRefs->mWeak == 0) {
                delete mRefs;
            }
        }
    }
    const_cast<weakref_impl*&>(mRefs) = NULL;
}

如果没有初始化过sp对象,则删除mRefs对象;如果Flag设定当前对象的生命周期由wp指针决定并且mWeak计数为0,也删除mRefs对象。

3.2 只有wp指针,没有sp指针的应用.

{

    wp<A> wpA(new A);

}

首先来看wp的构造函数:


template<typename T>
wp<T>::wp(const sp<T>& other)
    : m_ptr(other.m_ptr)
{
    if (m_ptr) {
        m_refs = m_ptr->createWeak(this);
    }

首先将A对象的指针赋予给m_ptr,可见在sp和wp中都保存有A对象的实际指针,但wp中并没有重载"->",所以wp并不能直接调用A对象的方法,并且由前面sp的知识,我们知道,在decStrong的时候,有可能A对象会被释放,并不会care 是否存在wp的引用。然后调用A对象的createWeak方法,实际上是调用RefBase的这个方法。注意的是在wp中,m_refs是weakref_type的指针;而在RefBase中,mRefs是weakref_impl的指针,所以在下面的代码返回时要注意类型的转型。

RefBase::weakref_type* RefBase::createWeak(const void* id) const
{
    mRefs->incWeak(id);
    return mRefs;
}
 
void RefBase::weakref_type::incWeak(const void* id)
{
    weakref_impl* const impl = static_cast<weakref_impl*>(this);
    impl->addWeakRef(id);
    const int32_t c = android_atomic_inc(&impl->mWeak);
    ALOG_ASSERT(c >= 0, "incWeak called on %p after last weak ref", this);
}

这里只会增加mWeak 计数,这是mStrong等于INITIAL_STRONG_VALUE,mWeak等于1。当wpA退出作用域后,调用wp的析构函数:

template<typename T>
wp<T>::~wp()
{
    if (m_ptr) m_refs->decWeak(this);
}

decWeak函数我们上面讲过,如果Flag设定当前对象的生命周期由sp指针决定,并且之前没有初始化过任何sp对象,则直接删除A对象;并在RefBase的析构函数中取释放mRefs对象。

3.3 既有sp指针,又有wp指针的应用

{

   sp<A> spA(new A)

    wp<A> wpA(spA);

}

从上面它们的构造函数我们知道,这是mStong等于1,mWeak等于2。在spA和wpA退出作用域时,首先调用wp的析构函数,再调用sp的析构函数。在wp析构函数中,只会减少mWeak计数为1,然后就然后了。再到sp的析构函数中,就和我们前面介绍的第一种应用一样了。

3.4 wp指针如果调用对象的方法

前面说过在wp中并没有重载"->",所以wp并不能直接调用A对象的方法,并且由前面sp的知识,我们知道,在decStrong的时候,有可能A对象会被释放,所以在wp中想要调用A对象的方法,必须获得sp指针,这是通过wp的promote方法实现的:

template<typename T>
sp<T> wp<T>::promote() const
{
    sp<T> result;
    if (m_ptr && m_refs->attemptIncStrong(&result)) {
        result.set_pointer(m_ptr);
    }
    return result;
}

这里调用weakref_type的attemptIncStrong方法去尝试增加mStrong计数:

bool RefBase::weakref_type::attemptIncStrong(const void* id)
{
    incWeak(id);
    
    weakref_impl* const impl = static_cast<weakref_impl*>(this);
    int32_t curCount = impl->mStrong;
 
    while (curCount > 0 && curCount != INITIAL_STRONG_VALUE) {
        if (android_atomic_cmpxchg(curCount, curCount+1, &impl->mStrong) == 0) {
            break;
        }
        curCount = impl->mStrong;
    }
    
    if (curCount <= 0 || curCount == INITIAL_STRONG_VALUE) {
        if ((impl->mFlags&OBJECT_LIFETIME_WEAK) == OBJECT_LIFETIME_STRONG) {
            if (curCount <= 0) {
                decWeak(id);
                return false;
            }
 
            while (curCount > 0) {
                if (android_atomic_cmpxchg(curCount, curCount + 1,
                        &impl->mStrong) == 0) {
                    break;
                }
                curCount = impl->mStrong;
            }
 
            if (curCount <= 0) {
                decWeak(id);
                return false;
            }
        } else {
            if (!impl->mBase->onIncStrongAttempted(FIRST_INC_STRONG, id)) {
                decWeak(id);
                return false;
            }
            curCount = android_atomic_inc(&impl->mStrong);
        }
 
        if (curCount > 0 && curCount < INITIAL_STRONG_VALUE) {
            impl->mBase->onLastStrongRef(id);
        }
    }
    
    impl->addStrongRef(id);
 
    curCount = impl->mStrong;
    while (curCount >= INITIAL_STRONG_VALUE) {
        if (android_atomic_cmpxchg(curCount, curCount-INITIAL_STRONG_VALUE,
                &impl->mStrong) == 0) {
            break;
        }
        curCount = impl->mStrong;
    }
 
    return true;
}

首先调用incWeak来增加mWeak计数,因为这里需要获取sp指针,在sp的构造函数我们知道,会同时增加mWeak和mStrong值。然后根据mStong值分两种情况讨论:

  1. 当前面存在sp的引用,即curCount > 0 && curCount != INITIAL_STRONG_VALUE,这时直接让mStrong加1。

2.当前面不存在sp的引用,需要结合Flag去判断。又分为以下几种情况:

       一. Flag = OBJECT_LIFETIME_STRONG,并且curCount等于0。说明之前的sp对象已经释放,由前面的知识我们知道,在释放sp对象的同时也会释放对象A,所以这里调用decWeak来释放前面增加的一次mWeak值并返回false

       二.Flag = OBJECT_LIFETIME_STRONG,并且curCount = INITIAL_STRONG_VALUE,说明前面没有sp引用,这时我们可以增加mStrong值。

       三.Flag = OBJECT_LIFETIME_WEAK,并且curCount <= 0 || curCount == INITIAL_STRONG_VALUE,则调用RefBase的onIncStrongAttempted去尝试增加mStrong值

当上面任何一种情况增加了mStrong值以后,mSrong的值可能大于INITIAL_STRONG_VALUE,我们需要去修正mStrong,就是通过减去INITIAL_STRONG_VALUE计算。当attemptIncStrong返回true时,promote方法就会调用sp的set_pointer方法去设置StrongPointer中的实际A对象的指针。接下来就可以通过sp调用相关的方法了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值