解釋清楚智能指針二【用本身的話,解釋清楚】

寫在前面

用本身的話分析清楚~android

 

智能指針是如何使用的?app

強指針是如何實現?函數

弱指針如何轉化爲強指針?ui

智能指針的使用

智能指針的使用必須知足以下條件:this

這個類須要繼承自RefBaseatom

 

爲何須要虛析構函數?spa

虛析構函數是爲了解決這樣的一個問題:基類指針指向派生類對象,並用基類的指針刪除派生類對象。虛函數的出現是爲了解決多態問題。設計

 

知足上述條件的類就能夠定義智能指針了,普通的指針使用以下方式:指針

MyClass *p_obj;orm

智能指針是這樣定義:

Sp<MyClass> p_obj;

 

強指針的使用:

        MyClass *p_obj;

1 p_obj = new MyClass(); // 注意不要寫成 p_obj = new sp<MyClass>  

2 sp<MyClass> p_obj2 = p_obj;  

3 p_obj->func();  

4 p_obj = create_obj();  

5 some_func(p_obj);  

弱指針的使用:

1   wp<MyClass> wp_obj = new MyClass();  

2 p_obj = wp_obj.promote(); // 升級爲強指針。不過這裏要用.而不是->,真是有負其指針之名啊  

3   wp_obj = NULL;  

 

與普通指針相比,智能指針的特色

  1. 智能指針解決了對象自動釋放的問題
  2. 智能指針其實更像引用
  3. 智能指針與普通指針相比,消耗更多的資源。

設計原理

智能指針是經過強弱引用計數來維護一個對象的生命週期的,若是強引用計數小於零的時候,會自動釋放空間資源。

咱們結合內部的實現,分析一下這段代碼的執行:

  1. MyClass *p_obj;
  2. p_obj = new MyClass(); // 注意不要寫成 p_obj = new sp<MyClass>  
  3. sp<MyClass> p_obj2 = p_obj;  
  4. p_obj->func();  
  5. p_obj = create_obj();  
  6. some_func(p_obj);  

 

 

 

咱們按照程序的執行流程來分析下內部代碼的實現

源碼位於:

http://androidxref.com/4.4.3_r1.1/xref/system/core/libutils/RefBase.cpp

http://androidxref.com/4.4.3_r1.1/xref/system/core/include/utils/RefBase.h

 

MyClass *p_obj;

p_obj = new MyClass(); // 注意不要寫成 p_obj = new sp<MyClass>  

 

MyClass繼承自RefBase,因此:

 

579RefBase::RefBase()

580    : mRefs(new weakref_impl(this))

581{

582}

 

初始化了成員變量mRefs

 

70    weakref_impl(RefBasebase)

71        : mStrong(INITIAL_STRONG_VALUE)

72        , mWeak(0)

73        , mBase(base)

74        , mFlags(0)

75    {

76    }

 

62public:

63    volatile int32_t    mStrong;    //強引用計數

64    volatile int32_t    mWeak; //弱引用計數

65    RefBase* const      mBase;

66    volatile int32_t    mFlags;

67

其中mFlags 用來描述對象的生命週期控制方式。取值可使

131    //! Flags for extendObjectLifetime()

132    enum {

133        OBJECT_LIFETIME_STRONG  = 0x0000,  //只與強引用計數有關

134        OBJECT_LIFETIME_WEAK    = 0x0001,

135        OBJECT_LIFETIME_MASK    = 0x0001

136    };

http://androidxref.com/4.4.3_r1.1/xref/system/core/include/utils/RefBase.h

 

這裏初始化了目標對象,對象內部初始化了強弱引用計數,及控制對象生命週期模式。

 

  1. sp<MyClass> p_obj2 = p_obj;  

 

結合第一部分對sp實現的描述,

112template<typename T>

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

114        : m_ptr(other) {

115    if (other)

116        other->incStrong(this);

117}

 

使用傳遞來的形參初始化m_ptr, 這實際上是對目標對象多了一次引用,因此這裏調用incStrong(this)來增長一個強引用計數。

 

 

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

319{

320    weakref_impl* const refs = mRefs;

321    refs->incWeak(id);

322

323    refs->addStrongRef(id);

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

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

326#if PRINT_REFS

327    ALOGD("incStrong of %p from %p: cnt=%d\n", this, id, c);

328#endif

329    if (c != INITIAL_STRONG_VALUE)  {

330        return;

331    }

332 //若是等於初值,說明是第一次,則先減去初值。調用函數onFirstRef()

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

334    refs->mBase->onFirstRef();

335}

In  RefBase.cpp 實現,用戶的程序中,若有須要可重載之。

610void RefBase::onFirstRef()

611{

612}

 

 

 

387void RefBase::weakref_type::incWeak(const void* id)

388{

389    weakref_impl* const impl = static_cast<weakref_impl*>(this);

390    impl->addWeakRef(id);

391    const int32_t c = android_atomic_inc(&impl->mWeak);

392    ALOG_ASSERT(c >= 0, "incWeak called on %p after last weak ref", this);

393}

 

68#if !DEBUG_REFS

69

70    weakref_impl(RefBasebase)

71        : mStrong(INITIAL_STRONG_VALUE)

72        , mWeak(0)

73        , mBase(base)

74        , mFlags(0)

75    {

76    }

77

78    void addStrongRef(const void* /*id*/) { }

79    void removeStrongRef(const void* /*id*/) { }

80    void renameStrongRefId(const void* /*old_id*/, const void* /*new_id*/) { }

81    void addWeakRef(const void* /*id*/) { }

82    void removeWeakRef(const void* /*id*/) { }

83    void renameWeakRefId(const void* /*old_id*/, const void* /*new_id*/) { }

84    void printRefs() const { }

85    void trackMe(bool, bool) { }

86

87#else

咱們看到在release版本中addWeakRef(const void* /*id*/)等爲空函數。

由調用系統函數android_atomic_inc()  實現對&impl->mWeak增長。

 

最終的計數單元實際上是在對象中的weakref_type*   m_refs;中的mWeakmStrong.

 

接下來咱們看隨着sp指針做用域的結束,其調用自身的析構函數對對象內的計數自減操做。

 

下面看sp的析構函數的定義

http://androidxref.com/4.4.3_r1.1/xref/system/core/include/utils/StrongPointer.h

140template<typename T>

141sp<T>::~sp() {

142    if (m_ptr)

143        m_ptr->decStrong(this);

144}

 

 

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

338{

339    weakref_impl* const refs = mRefs;

340    refs->removeStrongRef(id);

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

342#if PRINT_REFS

343    ALOGD("decStrong of %p from %p: cnt=%d\n", this, id, c);

344#endif

345    ALOG_ASSERT(c >= 1, "decStrong() called on %p too many times", refs);

346    if (c == 1) {

//這裏說明引用的次數已經爲0android_atomic_dec()函數返回的是執行以前的值。

//調用對象的結束前的函數onLastStrongRef(id);

//釋放對象

347        refs->mBase->onLastStrongRef(id);

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

349            delete this;

350        }

351    }

352    refs->decWeak(id);

353}

 

 

總體分析下來,感受智能指針的整個代碼仍是比較簡單和清晰的。強弱引用計數具體的計數操做是在每一個對象中的成員變量:weakref_impl類型的mrefs實現的。weakref_impl  類型繼承自RefBase::weakref_typeRefBase::weakref_type其中定義了具體技術的實現,使用變量存儲強弱引用計數,使用android系統提供的原子操做對這些變量進行加減。提供封裝出變量的增長,減小函數供智能指針中的引用計數函數調用。 智能指針利用封裝的模板類的構造函數和析構函數自動的調用計數函數實現對對象的調用管理,當引用次數爲0時,釋放對象空間。

RefBase同時定義了函數

145    virtual void            onFirstRef(); 

146    virtual void            onLastStrongRef(const void* id);

147    virtual bool            onIncStrongAttempted(uint32_t flags, const void* id);

148    virtual void            onLastWeakRef(const void* id);

 

分別定義了第一次引用對象的時候執行的函數onFirstRef();

最後一次強引用對象時的函數onLastStrongRef(const void* id);

最後一次弱引用對象時的函數onLastWeakRef(const void* id);

 

 

在看看 wp弱指針

 

// 這個函數用於將wp指針升級爲sp指針

//其主要判斷m_ptr所指向的對象是否已經釋放以及是否能夠增長強指針計數

//若是ok,則返回強指針

440template<typename T>

441sp<T> wp<T>::promote() const

442{

443    sp<T> result;

444    if (m_ptr && m_refs->attemptIncStrong(&result)) {

445        result.set_pointer(m_ptr);

446    }

447    return result;

448}

 

 

428bool RefBase::weakref_type::attemptIncStrong(const void* id)

429{

430    incWeak(id);

431

432    weakref_impl* const impl = static_cast<weakref_impl*>(this);

433    int32_t curCount = impl->mStrong;

434

435    ALOG_ASSERT(curCount >= 0,

436            "attemptIncStrong called on %p after underflow", this);

437

438    while (curCount > 0 && curCount != INITIAL_STRONG_VALUE) {

439        // we're in the easy/common case of promoting a weak-reference

440        // from an existing strong reference.

441        if (android_atomic_cmpxchg(curCountcurCount+1, &impl->mStrong) == 0) {

442            break;

443        }

444        // the strong count has changed on us, we need to re-assert our

445        // situation.

446        curCount = impl->mStrong;

447    }

 

一個弱指針所引用的對象,可能處於兩種狀況。第一種狀況該對象同時也被其餘對象引用(此時其mStrong值應大於0,且不等於初值INITIAL_STRONG_VALUE)對於這種狀況比較好處理。

由於同一個對象可能有多個對象在引用,因此這裏加了這麼多判斷主要是爲了 數據的同步。

448

449    if (curCount <= 0 || curCount == INITIAL_STRONG_VALUE) {

450        // we're now in the harder case of either:

451        // - there never was a strong reference on us

452        // - or, all strong references have been released

453        if ((impl->mFlags&OBJECT_LIFETIME_WEAK) == OBJECT_LIFETIME_STRONG) {

454            // this object has a "normal" life-time, i.e.: it gets destroyed

455            // when the last strong reference goes away

456            if (curCount <= 0) {

457                // the last strong-reference got released, the object cannot

458                // be revived.

459                decWeak(id);

460                return false;

461            }

462

463            // here, curCount == INITIAL_STRONG_VALUE, which means

464            // there never was a strong-reference, so we can try to

465            // promote this object; we need to do that atomically.

466            while (curCount > 0) {

467                if (android_atomic_cmpxchg(curCountcurCount + 1,

468                        &impl->mStrong) == 0) {

469                    break;

470                }

471                // the strong count has changed on us, we need to re-assert our

472                // situation (e.g.: another thread has inc/decStrong'ed us)

473                curCount = impl->mStrong;

474            }

475

476            if (curCount <= 0) {

477                // promote() failed, some other thread destroyed us in the

478                // meantime (i.e.: strong count reached zero).

479                decWeak(id);

480                return false;

481            }

482        } else {

483            // this object has an "extended" life-time, i.e.: it can be

484            // revived from a weak-reference only.

485            // Ask the object's implementation if it agrees to be revived

486            if (!impl->mBase->onIncStrongAttempted(FIRST_INC_STRONGid)) {

487                // it didn't so give-up.

488                decWeak(id);

489                return false;

490            }

491            // grab a strong-reference, which is always safe due to the

492            // extended life-time.

493            curCount = android_atomic_inc(&impl->mStrong);

494        }

495

496        // If the strong reference count has already been incremented by

497        // someone else, the implementor of onIncStrongAttempted() is holding

498        // an unneeded reference.  So call onLastStrongRef() here to remove it.

499        // (No, this is not pretty.)  Note that we MUST NOT do this if we

500        // are in fact acquiring the first reference.

501        if (curCount > 0 && curCount < INITIAL_STRONG_VALUE) {

502            impl->mBase->onLastStrongRef(id);

503        }

504    }

505

506    impl->addStrongRef(id);

507

508#if PRINT_REFS

509    ALOGD("attemptIncStrong of %p from %p: cnt=%d\n", this, idcurCount);

510#endif

511

512    // now we need to fix-up the count if it was INITIAL_STRONG_VALUE

513    // this must be done safely, i.e.: handle the case where several threads

514    // were here in attemptIncStrong().

515    curCount = impl->mStrong;

516    while (curCount >= INITIAL_STRONG_VALUE) {

517        ALOG_ASSERT(curCount > INITIAL_STRONG_VALUE,

518                "attemptIncStrong in %p underflowed to INITIAL_STRONG_VALUE",

519                this);

520        if (android_atomic_cmpxchg(curCountcurCount-INITIAL_STRONG_VALUE,

521                &impl->mStrong) == 0) {

522            break;

523        }

524        // the strong-count changed on us, we need to re-assert the situation,

525        // for e.g.: it's possible the fix-up happened in another thread.

526        curCount = impl->mStrong;

527    }

528

529    return true;

530}

 

這裏結合代碼分析下,弱指針升級爲強指針的過程。

這塊隨後補上~

 

 

QQ羣 計算機科學與藝術  272583193

加羣連接:http://jq.qq.com/?_wv=1027&k=Q9OxMv

相關文章
相關標籤/搜索