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

写在前面

用自己的话分析清楚~

智能指针是如何使用的?

强指针是如何实现?

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

智能指针的使用

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

这个类需要继承自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;中的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_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

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

时间: 2024-08-01 15:36:14

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

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

写在前面 用自己的话解释清楚~ 智能指针是什么,可分为哪几种类型,各有什么特点,解决了什么问题,怎么解决的? 什么是智能指针? 智能指针是C++中的一个概念,主要是通过引用计数的方式,解决动态内存的自动释放问题(类似于Java .Python中的垃圾回收).主要解决程序常见的两个问题:动态的申请的内存没有释放:动态申请的内存释放后又被引用. 指针和引用的区别: 指针其实是一个变量,只不过它存储的是另一个变量的内存地址.而引用是另外一个变量的别名,它不占用空间.所以引用定义的时候必须初始化.引用访

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

前面讲到auto_ptr有个很大的缺陷就是所有权的转移,就是一个对象的内存块只能被一个智能指针对象所拥有.但我们有些时候希望共用那个内存块.于是C++ 11标准中有了shared_ptr这样的智能指针,顾名思义,有个shared表明共享嘛.所以shared_ptr类型的智能指针可以做为STL容器的元素 下面我们来瞧瞧shared_ptr具体是咋实现的.相较auto_ptr有下面几个不同的地方: 1.引进了一个计数器shared_count,用来表示当前有多少个智能指针对象共享指针指向的内存块 2

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

1. 几种智能指针 1. auto_ptr: c++11中推荐不使用他(放弃) 2. shared_ptr: 每添加一次引用 就+1,减少一次引用,就-1:做到指针进行共享 3. unique_ptr: 一个指针同时只能有一个使用者使用 4. weaked_ptr: 与shared_ptr搭配使用 1.1 weak_ptr 参考:https://zh.cppreference.com/w/cpp/memory/weak_ptr std::weak_ptr 是一种智能指针,它对被 std::sha

智能指针(二)--练习

智能指针--练习 #include<iostream> #include<string> #include<vector> #include<memory> #include<fstream> #include<initializer_list> using namespace std; class StrBlobPtr; //仅仅是声明,在该类为完全定义完整之前,只能使用其类型,而不能调用其成员和函数 class StrBlob {

Android架构分析之Android智能指针(二)

作者:刘昊昱 博客:http://blog.csdn.net/liuhaoyutz Android版本:4.4.2 在上一篇文章中,我们分析了Android智能指针中的强指针sp,本文我们来分析弱指针wp.为什么需要弱指针wp呢?我们来考虑下面一种场景:有两个类CParent和CChild,CParent类中有一个智能指针指向CChild对象,CChild类中有一个智能指针指向CParent对象 class CParent :public LightRefBase<CParent> { --

C++primer第十二章读书笔记---动态内存与智能指针

    目前为止我们使用过的静态内存,栈内存和内存池,静态内存用来保存局部static对象.类static成员,以及定义在任何函数之外的成员.栈内存用来保存定义在函数内部的非static成员,分配在静态 内存或栈内存中的对象由编译器自动创建或销毁,对于栈对象仅在其定义的程序块运行时才有效,static对象在程序运行之前分配,程序结束时销毁.除了静态内存和栈内存外,每个程序还拥有一个内存池(堆)在堆上分配动态对象,当动态对象不再使用时,我们必须显示的销毁它.     (一).动态内存与智能指针  

C++ 智能指针详解 二

智能指针(smart pointer)是存储指向动态分配(堆)对象指针的类,用于生存期控制,能够确保自动正确的销毁动态分配的对象,防止内存泄露.它的一种通用实现技术是使用引用计数(reference count).智能指针类将一个计数器与类指向的对象相关联,引用计数跟踪该类有多少个对象共享同一指针.每次创建类的新对象时,初始化指针并将引用计数置为1:当对象作为另一对象的副本而创建时,拷贝构造函数拷贝指针并增加与之相应的引用计数:对一个对象进行赋值时,赋值操作符减少左操作数所指对象的引用计数(如果

ReactNative 4Android源码分析二: 《JNI智能指针之实现篇》

文/Tamic http://blog.csdn.net/sk719887916/article/details/53462268 回顾 上一篇介绍了<ReactNative4Android源码分析2: JNI智能指针之介绍篇>JNI智能指针与wrapper class的作用,下面将对它们的具体实现进行分析,并解答上篇提出的几个问题 前文回顾了java object在JNI中的引用对象jobject的3种类型.智能指针自然也有相应的如下类型: global_ref 全局指针与jobject全局

C++ template —— 智能指针(十二)

在管理动态分配的内存时,一个最棘手的问题就是决定何时释放这些内存,而智能指针就是用来简化内存管理的编程方式.智能指针一般有独占和共享两种所有权模型.------------------------------------------------------------------------------------------------------------20.1 holder和trule本节将介绍两种智能指针类型:holder类型独占一个对象:而trule可以使对象的拥有者从一个hold