android智能指针(wp、sp)学习总结

相关主题
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

智能指针:强指针sp,弱指针wp,轻量级指针LightRefBase。

相关文件:RefBase.h,RefBase.cpp,StrongPointer.h(注:参考代码android 4.2.2)。RefBase.h:定义了RefBase类定义,wp模板类定义和实现,以及LightRefBase类定义。RefBase.cpp:定义了RefBase类实现以及RefBase的嵌套类weakref_type的实现。StrongPointer.h:定义了sp模板类定义和实现。

RefBase类主要方法如下:

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

{

weakref_impl* const refs = mRefs;

refs->incWeak(id); // 增加一次弱引用计数

refs->addStrongRef(id); // 空函数

// 原子操作,增加一次强引用计数,返回的是refs->mStrong执行加1操作之前的值const int32_t c = android_atomic_inc(&refs->mStrong);

ALOG_ASSERT(c > 0, "incStrong() called on %p after last strong ref", refs);

// 第一次执行,c的值为INITIAL_STRONG_V ALUE

if (c != INITIAL_STRONG_V ALUE) {//从第二次开始执行后,此条件都成立,直接返回return;

}

// 执行操作,refs->mStrong + (-INITIAL_STRONG_V ALUE),第一次执行后强引用计数refs->mStrong值变为1

android_atomic_add(-INITIAL_STRONG_V ALUE, &refs->mStrong);

refs->mBase->onFirstRef(); //第一次执行会调用该方法,子类可以覆盖该方法。

}

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

{

weakref_impl* const refs = mRefs;

refs->removeStrongRef(id); // 空函数

// 原子操作,强引用计数减1,返回的是执行减1操作之前的值

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); // 子类可覆盖该方法

// mFlags值缺省为0

if ((refs->mFlags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG)

{

delete this;

}

}

refs->decWeak(id); // 弱引用计数减1

}

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

{

weakref_impl* const refs = mRefs;

refs->incWeak(id); // 弱引用计数加1

refs->addStrongRef(id); // 空函数

const int32_t c = android_atomic_inc(&refs->mStrong); // 强引用计数加1

ALOG_ASSERT(c >= 0, "forceIncStrong called on %p after ref count underflow",refs);

switch (c) {

case INITIAL_STRONG_V ALUE:

android_atomic_add(-INITIAL_STRONG_V ALUE, &refs->mStrong);// 强引用计数减INITIAL_STRONG_V ALUE

// fall through...

case 0:

refs->mBase->onFirstRef();

}

}

// 创建嵌套类对象

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

{

mRefs->incWeak(id); // 弱引用计数加1

return mRefs;

}

// 延长对象生命周期

void RefBase::extendObjectLifetime(int32_t mode)

{

android_atomic_or(mode, &mRefs->mFlags); // 修改mFlags的值为mode

}

// RefBase构造函数在实例化时,创建一个weakref_impl对象,并且将当前类对象的this指针作为参数传递给weakref_impl类构造函数,因此它们之间存在相互引用。RefBase::RefBase()

: mRefs(new weakref_impl(this)) {

}

RefBase::~RefBase()

{

if (mRefs->mStrong == INITIAL_STRONG_V ALUE) {

delete mRefs;

} else {

if ((mRefs->mFlags & OBJECT_LIFETIME_MASK) != OBJECT_LIFETIME_STRONG) { if (mRefs->mWeak == 0) {

delete mRefs;

}

相关文档
最新文档