处理管理共享对象指针的类—enable_shared_from_this(STL源码)

enable_shared_from_this他的类内部就有一个weak_ptr,用于指向(保存)派生类被引用的计数信息,std::shared_ptr<派生类> p(new 派生类());weak计数将是1;wp = shared_from_this()会使得weak计数+1,变成2,外部保存了wp,即便p.reset()释放内存(delet数据对象),但是内部计数对象没有被delete,其weak计数为1,shared计数为0;计数对象是在weak=0时才会被释放,即shared计数=0时delete 数据ptr;weak=0时释放delete this;所以当wp.lock()时会生成一个shared_ptr A;lock()里在生成A是判断shared计数是否为0,=0则A的数据对象和指针对象都是空的,否则都是指向wp的,如果都是空则表示  该派生类已经析构了,否则就是还能访问

使用参考:C++11新特性之十:enable_shared_from_this_草上爬的博客-CSDN博客_std::enable_shared_from_this

以下模板函数_Enable_shared被调用处为:智能指针被构造(_Resetp0)的时候

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

template<class _Ty>
inline void _Enable_shared(_Ty *_Ptr, _Ref_count_base *_Refptr,	typename _Ty::_EStype * = 0)
{	// reset internal weak pointer
	if (_Ptr)
		_Do_enable(_Ptr,(enable_shared_from_this<typename _Ty::_EStype>*)_Ptr, _Refptr);
}

// TEMPLATE CLASS enable_shared_from_this
template<class _Ty>
class enable_shared_from_this
{	// provide member functions that create shared_ptr to this	提供为此创建shared_ptr的成员函数
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修饰的变量,将永远处于可变的状态,即使在一个const函数中
	mutable weak_ptr<_Ty> _Wptr;
};

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值