【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

相关推荐
巴伦是只猫42 分钟前
【深度学习笔记】3 step by step (jupyter)
笔记·深度学习·jupyter
papership44 分钟前
【入门级-C++程序设计:12、文件及基本读写-文件的基本概念&文本文件的基本操作】
开发语言·c++·青少年编程
心平愈三千疾7 小时前
学习秒杀系统-实现秒杀功能(商品列表,商品详情,基本秒杀功能实现,订单详情)
java·分布式·学习
岁忧8 小时前
(nice!!!)(LeetCode 面试经典 150 题 ) 30. 串联所有单词的子串 (哈希表+字符串+滑动窗口)
java·c++·leetcode·面试·go·散列表
SunkingYang9 小时前
MFC/C++语言怎么比较CString类型最后一个字符
c++·mfc·cstring·子串·最后一个字符·比较
界面开发小八哥9 小时前
MFC扩展库BCGControlBar Pro v36.2新版亮点:可视化设计器升级
c++·mfc·bcg·界面控件·ui开发
R-G-B9 小时前
【15】MFC入门到精通——MFC弹窗提示 MFC关闭对话框 弹窗提示 MFC按键触发 弹窗提示
c++·mfc·mfc弹窗提示·mfc关闭弹窗提示·mfc按键触发 弹窗提示
艾莉丝努力练剑9 小时前
【数据结构与算法】数据结构初阶:详解顺序表和链表(四)——单链表(下)
c语言·开发语言·数据结构·学习·算法·链表
十秒耿直拆包选手9 小时前
Qt:QCustomPlot类介绍
c++·qt·qcustomplot
珊瑚里的鱼9 小时前
第十三讲 | map和set的使用
开发语言·c++·笔记·visualstudio·visual studio