admin管理员组文章数量:1667254
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://wwwblogs/Jackwen/p/4335786.html
版权声明:本文标题:RefBase, sp和wp (2) 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dianzi/1730077564a1221979.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论