智能指針派生類—weak_ptr(STL源碼)


// TEMPLATE CLASS weak_ptr
// weak_ptr智能指針類模板(指向由智能指針管理的對象,增加弱引用計數,若爲shared_ptr不增加的引用計數(非弱))
template<class _Ty>
class weak_ptr
	: public _Ptr_base<_Ty>// 繼承自智能指針基類
{	// class for pointer to reference counted resource	指向引用計數資源的指針的類
public:
	weak_ptr() _NOEXCEPT
	{	// construct empty weak_ptr object
	}
	// copy構造函數
	weak_ptr(const weak_ptr& _Other) _NOEXCEPT
	{	// construct weak_ptr object for resource pointed to by _Other
		this->_Resetw(_Other);// 同時遞增弱引用計數
	}

		template<class _Ty2,
	class = typename enable_if<is_convertible<_Ty2 *, _Ty *>::value,
		void>::type>
		weak_ptr(const shared_ptr<_Ty2>& _Other) _NOEXCEPT
	{	// construct weak_ptr object for resource owned by _Other
		this->_Resetw(_Other);
	}

		template<class _Ty2,
	class = typename enable_if<is_convertible<_Ty2 *, _Ty *>::value,
		void>::type>
		weak_ptr(const weak_ptr<_Ty2>& _Other) _NOEXCEPT
	{	// construct weak_ptr object for resource pointed to by _Other
		this->_Resetw(_Other.lock());
	}

		~weak_ptr() _NOEXCEPT
	{	// release resource
		this->_Decwref();// 遞減弱引用計數
	}

		weak_ptr& operator=(const weak_ptr& _Right) _NOEXCEPT
	{	// assign from _Right
		this->_Resetw(_Right);
		return (*this);
	}

		template<class _Ty2>
	weak_ptr& operator=(const weak_ptr<_Ty2>& _Right) _NOEXCEPT
	{	// assign from _Right
		this->_Resetw(_Right.lock());
		return (*this);
	}

		template<class _Ty2>
	weak_ptr& operator=(const shared_ptr<_Ty2>& _Right) _NOEXCEPT
	{	// assign from _Right
		this->_Resetw(_Right);
		return (*this);
	}

		void reset() _NOEXCEPT
	{	// release resource, convert to null weak_ptr object
		this->_Resetw();
	}

		void swap(weak_ptr& _Other) _NOEXCEPT
	{	// swap pointers
		this->_Swap(_Other);
	}

		bool expired() const _NOEXCEPT
	{	// return true if resource no longer exists
		return (this->_Expired());
	}

	//	調用explicit shared_ptr(const weak_ptr<_Ty2>& _Other,bool _Throw = true)
		shared_ptr<_Ty> lock() const _NOEXCEPT
	{	// convert to shared_ptr
		return (shared_ptr<_Ty>(*this, false));// 如果引用計數不爲0,則返回一個其非空的shared_ptr臨時對象,此時引用計數+1,若調用處臨時對象未被賦值,則析構,計數-1
	}
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章