RefBase, sp和wp (2)

本文介绍从弱指针(wp)转换为强指针(sp)的过程,并详细解析了promote函数的具体实现细节,包括如何调整引用计数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 通过wp创建sp的例子, 如:

    int main() {

        A* pA = new A();

        wp<A> wpA(pA);                             // 弱引用计数为1, 强引用计数为初始值0x1000000.

        sp<A> spA = wpA.promote();             // 通过promote()得到一个sp.

    }

2. promote函数的实现:

    template<typename T>

    sp<T> wp<T>::promote() const {

        retrun sp<T>(m_ptr, m_refs);               // 调用sp的构造函数。

    }

3. template<typename T>

sp<T>::sp(T* p, weakref_type* refs)

    : m_ptr((p && refs->attemptIncStrong(this)) ? p : 0){

}

4. bool RefBase::weakref_type::attemptIncStrong(const void* id) {

    incWeak(id);        // 增加若引用计数,此时弱引用计数为2.

    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) {

        bool allow;

       if (curCount == INITIAL_STRONG_VALUE) {

            allow = (impl->mFlags&OBJECT_LIFETIME_WEAK) != OBJECE_LIFETIME_WEAK || impl->mBase->onIncStrongAttempted(FIRST_INC_STRONG, id);

       } else {

            allow = (impl->mFlags&OBJECT_LIFETIME_WEAK) != OBJECE_LIFETIME_WEAK && impl->mBase->onIncStrongAttempted(FIRST_INC_STRONG, id);

       }

       if (!allow) {

           decWeak(id);         // 不允许由弱生强,若引用计数减1,进来时已加1.

           return false;

       }

       curCount = android_atomic_inc(&impl->mStrong);       // 允许由弱生强,强引用计数加1.

       if (curCount > 0 && curCount < INITIAL_STRONG_VALUE) {

               impl->mBase->onLastStrongRef(id);

      }

    }

    if (curCount == INITIAL_STRONG_VALUE) {

        android_atomic_add(-INITIAL_STRONG_VALUE, &impl->mStrong);           // 强引用计数变为1.

        impl->mBase->onFirstRef();

    }

    return true;

}

转载于:https://www.cnblogs.com/Jackwen/p/4335786.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值