1. Example of creating an SP through WP, such as:
int main () {
A * PA = new A ();
Wp<a> WpA (PA); The weak reference count is 1, and the strong reference count is the initial value 0x1000000.
sp<a> SpA = Wpa.promote (); Get an SP through promote ().
}
2. Implementation of the promote function:
Template<typename t>
Sp<t> wp<t>::p romote () const {
Retrun sp<t> (m_ptr, m_refs); Call the SP constructor.
}
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); Adds a reference count, at which point the weak reference count is 2.
weakref_impl* Const IMPL = static_cast<weakref_impl*> (this);
int32_t Curcount = impl->mstrong; This is still the initial value
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); The weak is not allowed to be strong, if the reference count minus 1, came in with the addition of 1.
return false;
}
Curcount = Android_atomic_inc (&impl->mstrong); Allowed by weak to strong, strong reference count plus 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); The strong reference count becomes 1.
Impl->mbase->onfirstref ();
}
return true;
}
Refbase, SP and WP (2)