Notes on std::enable_shared_from_this

notes

Note: std::weak_ptr can be found in

enable_shared_from_this is implemented through weak_ptr. When creating this derived class object smart pointer, the weak_ptr pointer will be initialized. Looking at the source code, we can see that _Resetp0 will be called in the constructor of shared_ptr, and then the _Do_enable function will be called indirectly, and _Do_enable will set the weak_ptr pointer. From this we can also know that if you want to use enable_shared_from_this, you must create a smart pointer, otherwise the weak_ptr pointer will not be initialized, and subsequent shared_from_this calls will naturally cause problems. The calling sequence is as follows:

	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 implementation code

	// 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;
	};

Guess you like

Origin blog.csdn.net/s634772208/article/details/130203404