enable_shared_from_this
什么是enable_shared_from_this?
这是一个模板类,来自boost库,后被加进C++11标准。通过继承该类,可以让派生类有办法产生这个类的实例的智能指针shared_ptr。
使用方法
class T:public enable_shared_from_this<T>{
public:
shared_ptr<T> get_shared(){
return shared_from_this();
}
void f(){}
};
int main(){
shared_ptr<T> t1 (new T);
shared_ptr<T> t2 = t1->get_shared();
return;
}
通过这种方式,t1,t2这两个智能指针指向了同一个类T的实例。
用处
当回调函数是类的成员函数时,要保证类的生命周期长于回调函数被使用的时间点。这个类一般要继承enable_shared_from_this模板类。
例如,在T类里:
std::bind(f,shared_from_this());
如果被别的类或程序回调,这样就能保证类对象的生命期。
为何不用this
原因之一是保证类对象在回调执行时的生命期。
get_shared返回shared_ptr<\T>(this)行吗
这样会导致同一个this生成多个毫不相关的shared_ptr(this),程序会析构多次。