C++ 11的提供了一个模板类std::enable_shared_from_this。
目的
为安全获取当前对象的shared_ptr提供方便。
原因
一般在对象的函数中,是不可以返回一个指向this指针的shared_ptr。因为如果当前对象已经析构,当shared_ptr再次析构时,因为其管理的指针已经不再合法,所以会导致Undefined行为。
如果实在有这种需求,就应该使用std::enable_shared_from_this
提供的shared_from_this
方法获取。
使用
class SomeCls : public std::enable_shared_from_this<SomeCls>{
...
};
SomeCls a;
std::shared_ptr<SomeCls> pa = a.shared_from_this();
pa->someMethod();