shared_from_this()的用途

资源对象的成员方法(不包括构造函数和析构函数)需要获取指向对象自身,即包含了this指针的shared_ptr

使用原因

1.把当前类对象作为参数传给其他函数时,为什么要传递share_ptr呢?直接传递this指针不可以吗?

一个裸指针传递给调用者,谁也不知道调用者会干什么?假如调用者delete了该对象,而share_tr此时还指向该对象。

2.这样传递share_ptr可以吗?share_ptr <this>

这样会造成2个非共享的share_ptr指向一个对象,最后造成2次析构该对象。

使用示例

#include<iostream>
#include<memory>
using namespace std;
class Base : public std::enable_shared_from_this<Base>
{
private:
/* data */
public:
Base(/* args */){ cout << "constructor.."<< endl;}
~Base(){ cout << "delete.."<< endl; }
std::shared_ptr<Base> getSharedFromThis(){return shared_from_this();}
//注意获取共享指针的函数不能在析构函数或者析构的回调函数中调用
void fun(){
std::shared_ptr<Base> basePtr = enable_shared_from_this::shared_from_this();
cout<< "use_count:"<< basePtr.use_count() <<endl; //应用计数+2 说明获取共享指针成功

}
};

class none_donging{
public:
void operator()(void* val){
Base *base = (Base *)val;
if (base)
{
delete base;
}
}
};

typedef std::shared_ptr<Base> BasePtr;

int main(){
{
BasePtr basePtr = BasePtr(new Base,[=](void* val){
//自定义析构
Base* base = (Base*)val;
if(base){
// base->fun(); //禁止在析构的回调函数中调用
delete base;
}
});
basePtr->fun();
}
cout <<"==================="<<endl;
{
BasePtr basePtr = BasePtr(new Base,none_donging());
BasePtr basePtr3 = basePtr->getSharedFromThis();
cout<< "use_count:"<< basePtr3.use_count() <<endl;
}
return 0;
}

输出:

constructor..
use_count:2
delete..
===================
constructor..
use_count:2
delete..