C++11智能指针(四)

2014-11-24 11:29:00 · 作者: · 浏览: 4
& _Right)
: _Ptr(0), _Rep(0)
{ // construct _Ptr_base object that takes resource from _Right
_Assign_rv(_STD forward<_Myt>(_Right));
}
template
_Ptr_base(_Ptr_base<_Ty2>&& _Right)
: _Ptr(_Right._Ptr), _Rep(_Right._Rep)
{ // construct _Ptr_base object that takes resource from _Right
_Right._Ptr = 0;
_Right._Rep = 0;
}
复制代码
_Ptr_base的默认构造函数是指针置位nullptr,这没什么好说的。剩下两个是转移构造函数,比较奇怪的是
template
_Ptr_base(_Ptr_base<_Ty2>&& _Right)
接受以任意类型作为模板参数的_Ptr_base?不懂,估计与shared_ptr向上转型有关。
------------------------------------------------------------ _Ptr_base的_Resetp函数 -------------------------------------------------------------
然后我们看一下_Resetp函数
复制代码
template
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 _Dx>
void _Resetp(_Ux *_Px, _Dx _Dt)
{ // release, take ownership of _Px, deleter _Dt
_TRY_BEGIN // allocate control block and reset
_Resetp0(_Px, new _Ref_count_del<_Ux, _Dx>(_Px, _Dt));
_CATCH_ALL // allocation failed, delete resource
_Dt(_Px);
_RERAISE;
_CATCH_END
}
//#if _HAS_CPP0X
template
class _Dx,
class _Alloc>
void _Resetp(_Ux *_Px, _Dx _Dt, _Alloc _Ax)
{ // release, take ownership of _Px, deleter _Dt, allocator _Ax
typedef _Ref_count_del_alloc<_Ux, _Dx, _Alloc> _Refd;
typename _Alloc::template rebind<_Refd>::other _Al = _Ax;
_TRY_BEGIN // allocate control block and reset
_Refd *_Ptr = _Al.allocate(1);
::new (_Ptr) _Refd(_Px, _Dt, _Al);
_Resetp0(_Px, _Ptr);
_CATCH_ALL // allocation failed, delete resource
_Dt(_Px);
_RERAISE;
_CATCH_END
}
复制代码
_Resetp函数有三个重载,实际上就是 是否带析构器_Dx 和 是否带构造器_Alloc, 这两个参数都用于引用计数,我们继续留到后面讨论。
_Resetp函数的三个重载里又都调用了_Resetp0
template
void _Resetp0(_Ux *_Px, _Ref_count_base *_Rx)
{ // release resource and take ownership of _Px
this->_Reset0(_Px, _Rx);
_Enable_shared(_Px, _Rx);
}
这里又调用了父类_Ptr_base的_Reset0 和另一个函数_Enable_shared
先看一下_Reset0
复制代码
void _Reset0(_Ty *_Other_ptr, _Ref_count_base *_Other_rep)
{ // release resource and take new resource
if (_Rep != 0)
_Rep->_Decref();
_Rep = _Other_rep;
_Ptr = _Other_ptr;
}
复制代码
就是检查一下当前_Ptr_base引用计数指针是否为空,非空就释放一个引用计数,然后更新指针值和引用计数值
(为什么叫_Reset0? 0表示最基本的Reset?)
再看一下_Enable_shared
复制代码
template
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*)_Ptr, _Refptr);
}
inline void _Enable_shared(const volatile void *, const volatile void *)
{ // not derived from enable_shared_from_this; do nothing
}
复制代码
这里用了模板的最特化匹配
当_Ty有定义_EStype这个类型名的时候(也就是_Ty继承于enable_shared_from_this<_Ty>的时