enable_shared_from_this他的类内部就有一个weak_ptr,用于指向(保存)派生类被引用的计数信息,std::shared_ptr<派生类> p(new 派生类());weak计数将是1;wp = shared_from_this()会使得weak计数+1,变成2,外部保存了wp,即便p.reset()释放内存(delet数据对象),但是内部计数对象没有被delete,其weak计数为1,shared计数为0;计数对象是在weak=0时才会被释放,即shared计数=0时delete 数据ptr;weak=0时释放delete this;所以当wp.lock()时会生成一个shared_ptr A;lock()里在生成A是判断shared计数是否为0,=0则A的数据对象和指针对象都是空的,否则都是指向wp的,如果都是空则表示 该派生类已经析构了,否则就是还能访问
使用参考:C++11新特性之十:enable_shared_from_this_草上爬的博客-CSDN博客_std::enable_shared_from_this
以下模板函数_Enable_shared被调用处为:智能指针被构造(_Resetp0)的时候
template<class _Ty1,class _Ty2>
inline void _Do_enable(_Ty1 *_Ptr,enable_shared_from_this<_Ty2> *_Es,_Ref_count_base *_Refptr)
{ // reset internal weak pointer
_Es->_Wptr._Resetw(_Ptr, _Refptr);
}
template<class _Ty>
inline void _Enable_shared(_Ty *_Ptr, _Ref_count_base *_Refptr, typename _Ty::_EStype * = 0)
{ // reset internal weak pointer
if (_Ptr)
_Do_enable(_Ptr,(enable_shared_from_this<typename _Ty::_EStype>*)_Ptr, _Refptr);
}
// TEMPLATE CLASS enable_shared_from_this
template<class _Ty>
class enable_shared_from_this
{ // provide member functions that create shared_ptr to this 提供为此创建shared_ptr的成员函数
public:
typedef _Ty _EStype;
shared_ptr<_Ty> shared_from_this()
{ // return shared_ptr
return (shared_ptr<_Ty>(_Wptr));
}
shared_ptr<const _Ty> shared_from_this() const
{ // return shared_ptr
return (shared_ptr<const _Ty>(_Wptr));
}
protected:
enable_shared_from_this() _NOEXCEPT
{ // construct (do nothing)
}
enable_shared_from_this(const enable_shared_from_this&) _NOEXCEPT
{ // construct (do nothing)
}
enable_shared_from_this&
operator=(const enable_shared_from_this&) _NOEXCEPT
{ // assign (do nothing)
return (*this);
}
~enable_shared_from_this() _NOEXCEPT
{ // destroy (do nothing)
}
private:
template<class _Ty1,
class _Ty2>
friend void _Do_enable(
_Ty1 *,
enable_shared_from_this<_Ty2>*,
_Ref_count_base *);
// 被mutable修饰的变量,将永远处于可变的状态,即使在一个const函数中
mutable weak_ptr<_Ty> _Wptr;
};
改