很多情况下需要把 this 指针当作 shared_ptr 使用。这个时候单纯 make_shared 是不生效的,需要要求 this 对应的类继承
std::enable_shared_from_this
写法如下:
class A : public std::enable_shared_from_this<A>
{
....
}
使用时以 shared_from_this() 代替 this:
//A* pa = new A(); //错误
std::shared_ptr<A> pa = std::make_shared<A>(); //正确
void A::Func(std::shared_ptr<A> p)
{
...
}
Func(shared_from_this());
另外需要主要的是 A 的创建必须是 make_shared ,而不能直接 new,否则会在运行时抛出错误 bad_weak_ptr 。