解释清楚智能指针二【用自己的话,解释清楚】

写在前面

用自己的话分析清楚~

 

智能指针是如何使用的?

强指针是如何实现?

弱指针如何转化为强指针?

智能指针的使用

智能指针的使用必须满足如下条件:

这个类需要继承自RefBase

 

为什么需要虚析构函数?

虚析构函数是为了解决这样的一个问题:基类指针指向派生类对象,并用基类的指针删除派生类对象。虚函数的出现是为了解决多态问题。

 

满足上述条件的类就可以定义智能指针了,普通的指针使用如下方式:

MyClass *p_obj;

智能指针是这样定义:

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

 

posted @ 2014-07-22 09:48  夏大王  阅读(587)  评论(0编辑  收藏  举报