使用參考:https://blog.csdn.net/caoshangpa/article/details/79392878
以下模板函數_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;
};