析构函数中不可以使用shared_from_this()

参考:https://www.icode9.com/content-4-492133.html

析构函数中不能直接使用 shared_from_this()

#include <memory>
#include <iostream>

struct A : public std::enable_shared_from_this<A>
{
    ~A()
    {
        auto this_ptr = shared_from_this(); // std::bad_weak_ptr exception here. 
        std::cout << "this: " << this_ptr;
    }
};

int main()
{
    auto a = std::make_shared<A>();
    a.reset();
    return 0;
}
g++ -std=c++11 destroyWithEnableFromThis.cpp 

编译成功

./a.out

运行失败。

在这里插入图片描述

如果class B中持有了另外一个class A对象,B的析构函数中调用A的函数,A的函数使用了shared_from_this, 不可以。

#include <memory>
#include <iostream>

using namespace std;

class A : public std::enable_shared_from_this<A>
{
public:
    ~A()
    {
        cout << "A destructor is called" << endl;
    }

    void onDestroy()
    {
        auto this_ptr = shared_from_this();
        cout << "A:this_ptr" << this_ptr << endl;
    }
};

class B
{
public:
    B() : m_a()
    {

    }
    ~B()
    {
        cout << "B destructor is called" << endl;
        m_a.onDestroy();
    }
private:
    A m_a;
};

int main()
{
    auto b = std::make_shared<B>();
    // b.reset();
    return 0;
}

运行结果:
在这里插入图片描述

如果class B中持有了另外一个class A对象的指针,B的析构函数中调用A的函数,A的函数使用了shared_from_this, 可以。

#include <memory>
#include <iostream>

using namespace std;

class A : public std::enable_shared_from_this<A>
{
public:
    ~A()
    {
        cout << "A destructor is called" << endl;
    }

    void onDestroy()
    {
        auto this_ptr = shared_from_this();
        cout << "A:this_ptr" << this_ptr << endl;
    }
};

class B
{
public:
    B() : m_a(make_shared<A>())
    {
        
    }
    ~B()
    {
        cout << "B destructor is called" << endl;
        m_a->onDestroy();
    }
private:
    std::shared_ptr<A> m_a;
};

int main()
{
    auto b = std::make_shared<B>();
    // b.reset();
    return 0;
}

运行结果:
在这里插入图片描述

!!!!! I do not know why?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值