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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值