C++智能指针enable_shared_from_this

enable_shared_from_this介绍

enable_shared_from_this其实是智能指针中的内容,它的作用就是用于在类的内部,返回一个this的智能指针。

对于enable_shared_from_this,初学者可能不明白它的使用场景和使用的必要性,可能有得童鞋们会问既然有了this这个指向自己的指针, 为什么还需要enable_shared_from_this这个东西呢,直接用this代替不就好了吗?

我们来看看以下代码例子,如果先不运行,你能看出什么问题吗?

c 复制代码
#include <iostream>
class Person{
public:
    Person() = default;
    ~Person(){

    };
    std::shared_ptr<Person> getPtr(){
        return std::shared_ptr<Person>(this);
    }
};

int main() {
    std::shared_ptr<Person> person = std::make_shared<Person>();
    std::shared_ptr<Person> person1 = person->getPtr();
    std::cout << "person.use_count() = " << person.use_count() << std::endl;
    std::cout << "person1.use_count() = " << person1.use_count() << std::endl;
    return 0;
}

以上代码运行崩溃报错了,这是为什么呢?

这是因为只有一个Person的指针,但是却被两个智能指针shared_ptr持有,而它们的引用计数都是1,因此当main函数运行完毕后两个智能指针释放时都对同一个Person指针进行释放导致的崩溃。

如果我们能让两个智能指针shared_ptr共享同一个引用计数,那么这个崩溃问题就迎刃而解了。而通过让Person继承基类enable_shared_from_this,然后在函数getPtr中 调用基类的shared_from_this就能返回一个this的智能指针,这样即可实现让多个智能指针共享同一个引用计数,而达到销毁时只释放一次的目的。这就是enable_shared_from_this存在的必要性, 这也是this无法替代的功能点。

如下是实例代码:

c 复制代码
#include <iostream>
class Person:public std::enable_shared_from_this<Person>{
public:
    Person() = default;
    ~Person(){

    };
    std::shared_ptr<Person> getPtr(){
        return shared_from_this();
    }
};

int main() {
    std::shared_ptr<Person> person = std::make_shared<Person>();
    std::shared_ptr<Person> person1 = person->getPtr();
    std::cout << "person.use_count() = " << person.use_count() << std::endl;
    std::cout << "person1.use_count() = " << person1.use_count() << std::endl;
    return 0;
}

通过运行调试打印,我们可以看到这person和person1这两个智能指针的引用计数都变为了2,这是正确的。

通过两个实例代码的对比,我们可以发现问题的根源所在就是我们在返回this的智能指针时,直接调用std::shared_ptr构造函数传入裸指针的方式构造一个智能指针, 而在之前的介绍中我们提到过使用智能指针shared_ptr时尽量使用std::make_shared进行智能指针的构造,避免直接调用std::shared_ptr构造函数传入裸指针的方式进行构造。

更多关于enable_shared_from_this的实践对比可以参照官网学习:en.cppreference.com/w/cpp/memor...

enable_shared_from_this的实现

我们通过源码的方式来分析下enable_shared_from_this的实现原理,enable_shared_from_this的源码非常简短:

arduino 复制代码
template<class _Tp>
class _LIBCPP_TEMPLATE_VIS enable_shared_from_this
{
    mutable weak_ptr<_Tp> __weak_this_;
protected:
    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
    enable_shared_from_this() _NOEXCEPT {}
    _LIBCPP_INLINE_VISIBILITY
    enable_shared_from_this(enable_shared_from_this const&) _NOEXCEPT {}
    _LIBCPP_INLINE_VISIBILITY
    enable_shared_from_this& operator=(enable_shared_from_this const&) _NOEXCEPT
        {return *this;}
    _LIBCPP_INLINE_VISIBILITY
    ~enable_shared_from_this() {}
public:
    _LIBCPP_INLINE_VISIBILITY
    shared_ptr<_Tp> shared_from_this()
        {return shared_ptr<_Tp>(__weak_this_);}
    _LIBCPP_INLINE_VISIBILITY
    shared_ptr<_Tp const> shared_from_this() const
        {return shared_ptr<const _Tp>(__weak_this_);}

#if _LIBCPP_STD_VER > 14
    _LIBCPP_INLINE_VISIBILITY
    weak_ptr<_Tp> weak_from_this() _NOEXCEPT
       { return __weak_this_; }

    _LIBCPP_INLINE_VISIBILITY
    weak_ptr<const _Tp> weak_from_this() const _NOEXCEPT
        { return __weak_this_; }
#endif // _LIBCPP_STD_VER > 14

    template <class _Up> friend class shared_ptr;
};

通过源码我们可以发现这是一个模版类,将自身类型以模版参数的形式传入到父类,这是典型的CRTP应用,关于CRTP之前我们已经介绍过了,这里不再累赘。感兴趣的童鞋们可以参考之前的博文:

C++之CRTP的使用

enable_shared_from_this对外只提供了一个weak_from_this公共方法,其内部通过以为弱引用的智能指针weak_ptr构造了一个shared_ptr,这里并没有什么问题, 问题这个弱引用的智能指针__weak_this_它是在哪里初始化的呢?我们通shared_ptr的构造函数可以发现,如果传入的weak_ptr没有初始化的话是会抛出异常崩溃的。

其实成员变量__weak_this_的初始化是在类的外部进行初始化的,它的奥秘就是源码的倒数第二行template <class _Up> friend class shared_ptr;,在如果有使用到该类的shared_ptr 时,shared_ptr则会初始化__weak_this_进行初始化。这一点我们是可以通过我们上述的实例代码测试出来的,比如我们将上述的实例代码的第14行std::shared_ptr<Person> person = std::make_shared<Person>();改为不使用智能指针, 而使用裸指针的方式,修改为 auto person = new Person;,同时注释掉第16行再运行是会崩溃的,这就是因为__weak_this_没有进行初始化的原因。

推荐阅读

C++进阶系列

关注我,一起进步。

相关推荐
小飞猪Jay2 小时前
C++面试速通宝典——13
jvm·c++·面试
rjszcb2 小时前
一文说完c++全部基础知识,IO流(二)
c++
小字节,大梦想3 小时前
【C++】二叉搜索树
数据结构·c++
吾名招财3 小时前
yolov5-7.0模型DNN加载函数及参数详解(重要)
c++·人工智能·yolo·dnn
我是哈哈hh4 小时前
专题十_穷举vs暴搜vs深搜vs回溯vs剪枝_二叉树的深度优先搜索_算法专题详细总结
服务器·数据结构·c++·算法·机器学习·深度优先·剪枝
憧憬成为原神糕手4 小时前
c++_ 多态
开发语言·c++
郭二哈4 小时前
C++——模板进阶、继承
java·服务器·c++
挥剑决浮云 -4 小时前
Linux 之 安装软件、GCC编译器、Linux 操作系统基础
linux·服务器·c语言·c++·经验分享·笔记
丶Darling.4 小时前
LeetCode Hot100 | Day1 | 二叉树:二叉树的直径
数据结构·c++·学习·算法·leetcode·二叉树
labuladuo5204 小时前
Codeforces Round 977 (Div. 2) C2 Adjust The Presentation (Hard Version)(思维,set)
数据结构·c++·算法