写在前面

用自己的话分析清楚~

智能指针是如何使用的?

强指针是如何实现?

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

智能指针的使用

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

这个类需要继承自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(RefBase* base)

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(RefBase* base)

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;中的mWeak,mStrong.

接下来我们看随着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) {

//这里说明引用的次数已经为0,android_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_type,RefBase::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(curCount, curCount+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(curCount, curCount + 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_STRONG, id)) {

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, id, curCount);

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(curCount, curCount-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

转载于:https://www.cnblogs.com/fly-fish/p/3859855.html

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

  1. C++ 智能指针(二) std::unique_ptr

    C++ STL智能指针系列: C++ 智能指针(一) std::auto_ptr C++ 智能指针(二) std::unique_ptr C++ 智能指针(三) std::shared_ptr C++ ...

  2. 智能指针(二):shared_ptr实现原理

    文章转自:http://blog.csdn.net/weiwenhp/article/details/8707969 版权归原作者! (原博文的评论中有反应该博文内容存在一些错误,读者请注意!!!!! ...

  3. 深入学习c++--智能指针(二) weak_ptr(打破shared_ptr循环引用)

    1. 几种智能指针 1. auto_ptr: c++11中推荐不使用他(放弃) 2. shared_ptr: 拥有共享对象所有权语义的智能指针 3. unique_ptr: 拥有独有对象所有权语义的智 ...

  4. cwinthread*线程指针怎么销毁结束_C++知识点:智能指针

    之前面试虾皮时问到了智能指针相关知识点,当时答的很没有条理,这里整理一下权当笔记. 根据<C++ Primer Plus>中的解释,智能指针是行为类似于指针的模板对象.当函数分配堆内存时, ...

  5. qt 如何 指针 自动 释放内存_要是面试官再问你智能指针的问题,就拿这篇文章“盘他”!!!...

    前一段时间,有不少朋友问我关于智能指针的问题,并且反映经常会在面试中被面试官问到,所以今天小豆君就来讲讲我对智能指针的理解,希望能对大家有所帮助 既然讲智能指针,我们就先来看看它为什么会出现. 1 传 ...

  6. c++11之智能指针

    目录 一,什么是智能指针 二,共享的智能指针shared_ptr 1. shared_ptr的初始化 3. 指定删除器 三,独占的智能指针unique_ptr 1. 初始化 2. 删除器 四, 弱引用 ...

  7. c++智能指针与引用计数

    一. 引用计数 先写一个简单的学生类 #include<iostream> #include <string.h> using namespace std;class stud ...

  8. bartender一行打印两个二次开发_C++ 智能指针和二叉树:图解层序遍历和逐层打印二叉树...

    作者:apocelipes  链接:https://www.cnblogs.com/apocelipes/p/10758692.html 二叉树是极为常见的数据结构,关于如何遍历其中元素的文章更是数不 ...

  9. C++中各种智能指针的实现及弊端(二)

    C++中各种智能指针的实现及弊端(二) 文章目录 C++中各种智能指针的实现及弊端(二) 一:实现auto_ptr 二.auto_ptr的问题及解决办法 一:实现auto_ptr C ++98版本的库 ...

最新文章

  1. iphone无线服务器未响应,iPhone无线充电断断续续或无法充电是什么原因?
  2. dycom游戏抽象空间框架正式版(alpha1.0)
  3. 一致性哈希算法介绍,及java实现
  4. 高级代码编辑器:sublime text 4 for Mac
  5. python将小数转为分数_Python分数
  6. P2665 [USACO08FEB]连线游戏Game of Lines
  7. 局域网屏幕共享_使用安卓手机作为树莓派的屏幕或ssh命令行终端
  8. MySQL模糊查询用法大全(正则、通配符,mybatis入门
  9. sumif单列求和_EXCEL条件求和函数SUMIF的几种常见用法
  10. SVN Cleanup失败的解决方法
  11. C#日期格式参考小结
  12. OHS 12C中导入第三方SSL证书
  13. 喜玛拉雅——徐薇翻唱合集
  14. ORB、SURF、SIFT特征点提取方法和ICP匹配方法
  15. ClickHouse到底牛逼在哪里?为什么比MySQL快831倍!
  16. 【Pytorch学习】Transforms
  17. html2canvas解决图片空白,网络图片跨域
  18. RGB和HSV颜色空间
  19. HTTP请求/响应报文头部结构
  20. 好橱柜彰显好品味,太子家居橱柜定制凸显家的气质

热门文章

  1. Java多线程_复习(更新中!!)
  2. 深入理解 WordPress 数据库中的用户数据 wp_user
  3. BroadcastReceiver广播接受者简单使用
  4. xe5 android sample 中的 SimpleList 是怎样绑定的
  5. C#:当把U盘放插入,然后程序自动将U盘的内容复制到本地硬盘
  6. nginx配置后重启无效与重启失败
  7. 险些被吓到!白宇代言新品万元荣耀8X售价原因揭秘
  8. intellij idea+easychm生成帮助文档
  9. 4 python 中 关于数值及运算
  10. shell 脚本初习