【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

相关推荐
十五年专注C++开发3 分钟前
同一线程有两个boost::asio::io_context可以吗?
c++·boost·asio·异步编程·io_context
中屹指纹浏览器31 分钟前
2025技术综述:指纹浏览器与国内IP适配的核心技术优化与实践
经验分享·笔记
xlq2232239 分钟前
26 avl树(下)
c++
叶子2024221 小时前
python学习--外星人入侵
学习
郝学胜-神的一滴1 小时前
深入理解OpenGL VBO:原理、封装与性能优化
c++·程序人生·性能优化·图形渲染
A24207349301 小时前
JavaScript学习
前端·javascript·学习
埃伊蟹黄面1 小时前
模拟算法思想
c++·算法·leetcode
im_AMBER1 小时前
weather-app开发手记 02 JSON基础 | API 调用 400 错误修复 | JWT 认证问题
笔记·学习·json·axios·jwt
小老鼠不吃猫1 小时前
深入浅出(六)序列化库 FlatBuffers、Protobuf、MessagePack
c++·开源·buffer
Unlyrical1 小时前
Valgrind快速使用
c++·valgrind