处理管理共享对象指针的类—enable_shared_from_this(STL源码)

使用参考:https://blog.csdn.net/caoshangpa/article/details/79392878

以下模板函数_Enable_shared被调用处为:智能指针被构造(_Resetp0)的时候

template 
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
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*)_Ptr, _Refptr);
}

// TEMPLATE CLASS enable_shared_from_this
template
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 shared_from_this() const
		{	// return shared_ptr
		return (shared_ptr(_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
		friend void _Do_enable(
			_Ty1 *,
			enable_shared_from_this<_Ty2>*,
			_Ref_count_base *);
	// 被mutable修饰的变量,将永远处于可变的状态,即使在一个const函数中
	mutable weak_ptr<_Ty> _Wptr;
};

 

你可能感兴趣的:(智能指针,STL)