【C++学习笔记】enable_shared_from_this

cpp 复制代码
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;
}

上面这个代码运行,会出错⚠️

因为getPtr内部通过原生的this指针去构造了一个智能指针并返回,导致两个智能指针personperson1同时管理一个对象,但是各自的引用计数都是1,导致析构两次,出错。

如果想要在类的内部返回一个这个类的智能指针应该先继承enable_shared_from_this,然后再返回shared_from_this(),就可以得到一个智能指针,并且这个智能指针与管理这个对象的智能指针共享引用计数

例子如下:

cpp 复制代码
#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;
}

https://mp.weixin.qq.com/s/WyYxzZ03zLkEnOnDjnUfuA

相关推荐
聪明的笨猪猪7 分钟前
Java Spring “IOC + DI”面试清单(含超通俗生活案例与深度理解)
java·经验分享·笔记·面试
lixinnnn.1 小时前
贪心:火烧赤壁
数据结构·c++·算法
im_AMBER1 小时前
Web 开发 24
前端·笔记·git·学习
Predestination王瀞潞1 小时前
类的多态(Num020)
开发语言·c++
Predestination王瀞潞1 小时前
类的继承(Num019)
开发语言·c++
Nuyoah11klay1 小时前
华清远见25072班C++学习假期10.3作业
c++
递归不收敛2 小时前
吴恩达机器学习课程(PyTorch 适配)学习笔记:3.4 强化学习
pytorch·学习·机器学习
烧冻鸡翅QAQ2 小时前
考研408笔记
笔记·考研
StarPrayers.2 小时前
卷积层(Convolutional Layer)学习笔记
人工智能·笔记·深度学习·学习·机器学习
Hard but lovely2 小时前
C++---》stl : pair 从使用到模拟实现
c++·后端