您的位置:首页 > 移动开发 > Android开发

Cubietruck---13.sp与wp分析_深入理解android第五章笔记

2016-06-28 18:26 453 查看
<深入理解android>卷1 邓凡平著的 第5章 深入理解常见类

class A: public RefBase

{

}

int main()

{

    A* pA = new A;       //1.

    sp<A> spA(pA);       //2.

    wp<A> wpA(spA);

}

1. new 的动作
1.1 执行RefBase的构造函数
其中类A继承自RefBase, 所以new A时,实际上执行了如下代码.
/work/ct/android42/frameworks/native/libs/utils/RefBase.cpp

RefBase::RefBase()

    : mRefs(new weakref_impl(this))

{

}

在RefBase的构造函数中又调用了weakref_impl的构造函数

1.2 执行RefBase的构造函数

weakref_impl(RefBase* base)

        : mStrong(INITIAL_STRONG_VALUE)

        , mWeak(0)

        , mBase(base)

        , mFlags(0)

        , mStrongRefs(NULL)

        , mWeakRefs(NULL)

        , mTrackEnabled(!!DEBUG_REFS_ENABLED_BY_DEFAULT)

        , mRetain(false)

    {

    }

1.3 关于wreakref_impl的说明
RefBase的内部类weakref_impl的定义如下:
在/work/ct/android42/frameworks/native/libs/utils/RefBase.cpp中

class RefBase::weakref_impl : public RefBase::weakref_type

{

    ...//省略

}

这是在定义了一个RefBase的一个内部类weakref_impl,
同时weakref_impl是继承自RefBase的另一个内部类weakref_type
这需要看一下class RefBase的定义
在/work/ct/android42/frameworks/native/include/utils/RefBase.h中
2. sp<A> spA(pA)分析
sp的类定义及构造函数都在/work/ct/android42/frameworks/native/include/utils/StrongPointer.h中

template<typename T>

sp<T>::sp(T* other)

: m_ptr(other)

  {

    if (other) other->incStrong(this);

  }

2.1 incStrong 将mStrong计数+1

void RefBase::incStrong(const void* id) const

{

    weakref_impl* const refs = mRefs;   
//weakref_impl* const mRefs;

    refs->incWeak(id);//将mWeak计数+1

    

    refs->addStrongRef(id);   //空

    //如是是第一次执行,因为mStrong初始化为INITIAL_STRONG_VALUE=10000,

    //需要把这个INITIAL_STRONG_VALUE减掉, 不是第一次执行就直接将mStrong计数+1

    const int32_t c = android_atomic_inc(&refs->mStrong);

    if(c != INITIAL_STRONG_VALUE)

        return ;

    android_atomic_add(-INITIAL_STRONG_VALUE, &refs->mStrong);

    refs->mBase->onFirstRef();    //执行一些初始化操作,这里略过分析

}

2.1.1 incWeak 将mWeak计数+1

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);  //将mWeak计数+1

}

执行sp<A> spA(pA)后mStrong与mWeak都加了1

3.wp<A> wpA(spA)分析
在/work/ct/android42/frameworks/native/include/utils/RefBase.h中

template<typename T>

wp<T>::wp(const sp<T>& other)

    : m_ptr(other.m_ptr)

{

    if (m_ptr) {

        m_refs = m_ptr->createWeak(this); //将mWeak计数+1

    }

}

在/work/ct/android42/frameworks/native/libs/utils/RefBase.cpp中

RefBase::weakref_type* RefBase::createWeak(const void* id) const

{

    mRefs->incWeak(id); //将mWeak计数+1

    return mRefs;

}

执行wp<A> wpA(spA)后只有mWeak加了1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: