Refbase, SP and WP (2)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.