• 【C++学习笔记】enable_shared_from_this


    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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    上面这个代码运行,会出错⚠️
    因为getPtr内部通过原生的this指针去构造了一个智能指针并返回,导致两个智能指针personperson1同时管理一个对象,但是各自的引用计数都是1,导致析构两次,出错。

    如果想要在类的内部返回一个这个类的智能指针应该先继承enable_shared_from_this,然后再返回shared_from_this(),就可以得到一个智能指针,并且这个智能指针与管理这个对象的智能指针共享引用计数

    例子如下:

    #include 
    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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    https://mp.weixin.qq.com/s/WyYxzZ03zLkEnOnDjnUfuA

  • 相关阅读:
    python报错 UnicodeDecodeError
    C#练习题18和19和20和21
    微调GPT3.5模型实例
    什么是电感?
    java反射的使用简单例子
    推荐国产神器Eolink!API优先,Eolink领先!
    java 函数式接口与Lambda表达式
    PHP 创建 MySQL 表
    dirty make clean
    极客打板——训练&测试
  • 原文地址:https://blog.csdn.net/qq_42961603/article/details/134367766