【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

相关推荐
QT 小鲜肉1 小时前
【C++基础与提高】第二章:C++数据类型系统——构建程序的基础砖石
开发语言·c++·笔记
songyuc4 小时前
【S2ANet】Align Deep Features for Oriented Object Detection 译读笔记
人工智能·笔记·目标检测
蒙奇D索大6 小时前
【算法】递归算法的深度实践:从布尔运算到二叉树剪枝的DFS之旅
笔记·学习·算法·leetcode·深度优先·剪枝
卡提西亚6 小时前
C++笔记-25-函数模板
c++·笔记·算法
R&L_201810017 小时前
C++之内联变量(Inline Variables)
c++·c++新特性
IT阳晨。8 小时前
【QT开发】交叉编译QT程序在ARMLinux平台上运行
c++·qt·交叉编译·armlinux·代码移植
派大星爱吃猫8 小时前
C++隐藏的this指针(详解)
c++·this指针
虾..9 小时前
C++ 哈希
开发语言·c++·哈希算法
liu****9 小时前
14.日志封装和线程池封装
linux·开发语言·c++
将编程培养成爱好9 小时前
C++ 设计模式《统计辅助功能》
开发语言·c++·设计模式·访问者模式