【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 分钟前
【C++实战⑦】C++函数实战:从基础到项目应用
c++·实战·函数
HMBBLOVEPDX8 分钟前
C++(静态函数)
开发语言·c++
张晓~1833994812133 分钟前
短视频矩阵源码-视频剪辑+AI智能体开发接入技术分享
c语言·c++·人工智能·矩阵·c#·php·音视频
The_Killer.1 小时前
格密码--从FFT到NTT(附源码)
学习·线性代数·密码学·格密码
四谎真好看2 小时前
Java 黑马程序员学习笔记(进阶篇6)
java·笔记·学习·学习笔记
mzhan0172 小时前
[笔记] 来到了kernel 5.14
笔记
星梦清河2 小时前
宋红康 JVM 笔记 Day17|垃圾回收器
java·jvm·笔记
一枝小雨2 小时前
【C++】list 容器操作
开发语言·c++·笔记·list·学习笔记
HMBBLOVEPDX2 小时前
C++(继承和多态)
开发语言·c++·继承和多态
Alice-YUE2 小时前
【css学习笔记8】html5css3新特性
css·笔记·学习