【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

相关推荐
姝孟1 分钟前
Linux学习笔记 1
linux·笔记·学习
dg101118 分钟前
go-zero学习笔记(六)---gozero中间件介绍
笔记·学习·golang
努力学习的小廉1 小时前
【智能指针】—— 我与C++的不解之缘(三十三)
开发语言·c++
baobao17676408301 小时前
C++单例模式
javascript·c++·单例模式
shenxiaolong_code1 小时前
编译器bug ?
c++·bug·meta programming·compiler bug
dami_king1 小时前
用C++手搓一个贪吃蛇?
c++·游戏·c
编程老菜鸡1 小时前
计算机网络笔记-分组交换网中的时延
笔记·计算机网络·智能路由器
Dovis(誓平步青云)1 小时前
【数据结构】排序算法(下篇·终结)·解析数据难点
c语言·数据结构·学习·算法·排序算法·学习方法·推荐算法
安於宿命2 小时前
【Linux】用C++实现UDP通信:详解socket编程流程
linux·c++·udp
愚润求学3 小时前
【C++】list模拟实现
开发语言·数据结构·c++·list