std::enable_shared_from_this的笔记

笔记

注:std::weak_ptr可参看

enable_shared_from_this通过weak_ptr来实现,在创建此派生类对象智能指针时,会初始化好weak_ptr指针。翻看源码可知,在shared_ptr的构造函数中会调用到_Resetp0,然后间接的最终会调用到_Do_enable函数,_Do_enable会设置好weak_ptr指针。从这也可以知道,若要用到enable_shared_from_this,则必须创建智能指针,否则weak_ptr指针不会初始化,后续的shared_from_this调用自然也会出问题。调用先后顺序如下:

	template<class _Ux>
		explicit shared_ptr(_Ux *_Px)
		{	// construct shared_ptr object that owns _Px
		_Resetp(_Px);
		}
template<class _Ux>
		void _Resetp(_Ux *_Px)
		{	// release, take ownership of _Px
		_TRY_BEGIN	// allocate control block and reset
		_Resetp0(_Px, new _Ref_count<_Ux>(_Px));
		_CATCH_ALL	// allocation failed, delete resource
		delete _Px;
		_RERAISE;
		_CATCH_END
		}
	template<class _Ux>
		void _Resetp0(_Ux *_Px, _Ref_count_base *_Rx)
		{	// release resource and take ownership of _Px
		this->_Reset0(_Px, _Rx);
		_Enable_shared(_Px, _Rx);
		}
	};
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);
	}

enable_shared_from_this 实现代码

	// TEMPLATE CLASS enable_shared_from_this
template<class _Ty>
	class enable_shared_from_this
	{	// provide member functions that create shared_ptr to this
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 weak_ptr<_Ty> _Wptr;
	};

你可能感兴趣的:(C/C++,shared_ptr)