智能指针派生类—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
	}
};

 

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