参考: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;
}
运行结果: