热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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

写在前面用自己的话分析清楚~智能指针是如何使用的?强指针是如何实现?弱指针如何转化为强指针?智能指针的使用智能指针的使用必须满足如下条件:这个类需要继承自RefBase为什么需要虚
写在前面

用自己的话分析清楚~

 

智能指针是如何使用的?

强指针是如何实现?

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

智能指针的使用

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

这个类需要继承自RefBase

 

为什么需要虚析构函数?

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

 

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

MyClass *p_obj;

智能指针是这样定义:

Sp p_obj;

 

强指针的使用:

        MyClass *p_obj;

1 p_obj = new MyClass(); // 注意不要写成 p_obj = new sp  

2 sp p_obj2 = p_obj;  

3 p_obj->func();  

4 p_obj = create_obj();  

5 some_func(p_obj);  

弱指针的使用:

1   wp 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  
  3. sp 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继承自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 p_obj2 = p_obj;  

 

结合第一部分对sp实现的描述,

112template

113sp::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(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;中的mWeakmStrong.

 

接下来我们看随着sp指针作用域的结束,其调用自身的析构函数对对象内的计数自减操作。

 

下面看sp的析构函数的定义

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

140template

141sp::~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_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

441sp wp::promote() const

442{

443    sp 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(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

 

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

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


推荐阅读
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • HDU 2372 El Dorado(DP)的最长上升子序列长度求解方法
    本文介绍了解决HDU 2372 El Dorado问题的一种动态规划方法,通过循环k的方式求解最长上升子序列的长度。具体实现过程包括初始化dp数组、读取数列、计算最长上升子序列长度等步骤。 ... [详细]
  • 本文介绍了lua语言中闭包的特性及其在模式匹配、日期处理、编译和模块化等方面的应用。lua中的闭包是严格遵循词法定界的第一类值,函数可以作为变量自由传递,也可以作为参数传递给其他函数。这些特性使得lua语言具有极大的灵活性,为程序开发带来了便利。 ... [详细]
  • 本文介绍了使用kotlin实现动画效果的方法,包括上下移动、放大缩小、旋转等功能。通过代码示例演示了如何使用ObjectAnimator和AnimatorSet来实现动画效果,并提供了实现抖动效果的代码。同时还介绍了如何使用translationY和translationX来实现上下和左右移动的效果。最后还提供了一个anim_small.xml文件的代码示例,可以用来实现放大缩小的效果。 ... [详细]
  • 向QTextEdit拖放文件的方法及实现步骤
    本文介绍了在使用QTextEdit时如何实现拖放文件的功能,包括相关的方法和实现步骤。通过重写dragEnterEvent和dropEvent函数,并结合QMimeData和QUrl等类,可以轻松实现向QTextEdit拖放文件的功能。详细的代码实现和说明可以参考本文提供的示例代码。 ... [详细]
  • 本文介绍了使用Java实现大数乘法的分治算法,包括输入数据的处理、普通大数乘法的结果和Karatsuba大数乘法的结果。通过改变long类型可以适应不同范围的大数乘法计算。 ... [详细]
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • 本文讨论了Alink回归预测的不完善问题,指出目前主要针对Python做案例,对其他语言支持不足。同时介绍了pom.xml文件的基本结构和使用方法,以及Maven的相关知识。最后,对Alink回归预测的未来发展提出了期待。 ... [详细]
  • 如何使用Java获取服务器硬件信息和磁盘负载率
    本文介绍了使用Java编程语言获取服务器硬件信息和磁盘负载率的方法。首先在远程服务器上搭建一个支持服务端语言的HTTP服务,并获取服务器的磁盘信息,并将结果输出。然后在本地使用JS编写一个AJAX脚本,远程请求服务端的程序,得到结果并展示给用户。其中还介绍了如何提取硬盘序列号的方法。 ... [详细]
  • 本文讨论了如何优化解决hdu 1003 java题目的动态规划方法,通过分析加法规则和最大和的性质,提出了一种优化的思路。具体方法是,当从1加到n为负时,即sum(1,n)sum(n,s),可以继续加法计算。同时,还考虑了两种特殊情况:都是负数的情况和有0的情况。最后,通过使用Scanner类来获取输入数据。 ... [详细]
  • 本文介绍了C#中数据集DataSet对象的使用及相关方法详解,包括DataSet对象的概述、与数据关系对象的互联、Rows集合和Columns集合的组成,以及DataSet对象常用的方法之一——Merge方法的使用。通过本文的阅读,读者可以了解到DataSet对象在C#中的重要性和使用方法。 ... [详细]
  • Mac OS 升级到11.2.2 Eclipse打不开了,报错Failed to create the Java Virtual Machine
    本文介绍了在Mac OS升级到11.2.2版本后,使用Eclipse打开时出现报错Failed to create the Java Virtual Machine的问题,并提供了解决方法。 ... [详细]
  • 在说Hibernate映射前,我们先来了解下对象关系映射ORM。ORM的实现思想就是将关系数据库中表的数据映射成对象,以对象的形式展现。这样开发人员就可以把对数据库的操作转化为对 ... [详细]
  • 知识图谱——机器大脑中的知识库
    本文介绍了知识图谱在机器大脑中的应用,以及搜索引擎在知识图谱方面的发展。以谷歌知识图谱为例,说明了知识图谱的智能化特点。通过搜索引擎用户可以获取更加智能化的答案,如搜索关键词"Marie Curie",会得到居里夫人的详细信息以及与之相关的历史人物。知识图谱的出现引起了搜索引擎行业的变革,不仅美国的微软必应,中国的百度、搜狗等搜索引擎公司也纷纷推出了自己的知识图谱。 ... [详细]
  • 本文讨论了使用差分约束系统求解House Man跳跃问题的思路与方法。给定一组不同高度,要求从最低点跳跃到最高点,每次跳跃的距离不超过D,并且不能改变给定的顺序。通过建立差分约束系统,将问题转化为图的建立和查询距离的问题。文章详细介绍了建立约束条件的方法,并使用SPFA算法判环并输出结果。同时还讨论了建边方向和跳跃顺序的关系。 ... [详细]
author-avatar
ltxys
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有