C++11智能指针(三)
typename add_reference<_Ty>::type operator*() const _NOEXCEPT
214 { // return reference to resource
215 return (*this->_Get());
216 }
217
218 _Ty *operator->() const _NOEXCEPT
219 { // return pointer to resource
220 return (this->_Get());
221 }
222
223 bool unique() const _NOEXCEPT
224 { // return true if no other shared_ptr object owns this resource
225 return (this->use_count() == 1);
226 }
227
228 _TYPEDEF_BOOL_TYPE;
229
230 _OPERATOR_BOOL() const _NOEXCEPT
231 { // test if shared_ptr object owns no resource
232 return (this->_Get() != 0 _CONVERTIBLE_TO_TRUE : 0);
233 }
234
235 private:
236 template
237 void _Resetp(_Ux *_Px)
238 { // release, take ownership of _Px
239 _TRY_BEGIN // allocate control block and reset
240 _Resetp0(_Px, new _Ref_count<_Ux>(_Px));
241 _CATCH_ALL // allocation failed, delete resource
242 delete _Px;
243 _RERAISE;
244 _CATCH_END
245 }
246
247 template
248 class _Dx>
249 void _Resetp(_Ux *_Px, _Dx _Dt)
250 { // release, take ownership of _Px, deleter _Dt
251 _TRY_BEGIN // allocate control block and reset
252 _Resetp0(_Px, new _Ref_count_del<_Ux, _Dx>(_Px, _Dt));
253 _CATCH_ALL // allocation failed, delete resource
254 _Dt(_Px);
255 _RERAISE;
256 _CATCH_END
257 }
258
259 //#if _HAS_CPP0X
260 template
261 class _Dx,
262 class _Alloc>
263 void _Resetp(_Ux *_Px, _Dx _Dt, _Alloc _Ax)
264 { // release, take ownership of _Px, deleter _Dt, allocator _Ax
265 typedef _Ref_count_del_alloc<_Ux, _Dx, _Alloc> _Refd;
266 typename _Alloc::template rebind<_Refd>::other _Al = _Ax;
267
268 _TRY_BEGIN // allocate control block and reset
269 _Refd *_Ptr = _Al.allocate(1);
270 ::new (_Ptr) _Refd(_Px, _Dt, _Al);
271 _Resetp0(_Px, _Ptr);
272 _CATCH_ALL // allocation failed, delete resource
273 _Dt(_Px);
274 _RERAISE;
275 _CATCH_END
276 }
277 //#endif /* _HAS_CPP0X */
278
279 public:
280 template
281 void _Resetp0(_Ux *_Px, _Ref_count_base *_Rx)
282 { // release resource and take ownership of _Px
283 this->_Reset0(_Px, _Rx);
284 _Enable_shared(_Px, _Rx);
285 }
286 };
复制代码
我们可以看到shared_ptr是继承于_Ptr_base的,(同时weak_ptr也继承与_Ptr_base)
那么我们先来看一下_Ptr_base里有什么东西
首先我们可以看到_Ptr_base里面有两个属性
private:
_Ty *_Ptr;
_Ref_count_base *_Rep;
从shared_ptr我们知道_Ptr_base是个模板,而_Ty是传到_Ptr_base里的模板参数,也就是指针的类型
所以我们知道 _Ptr 保存的值就是真正的指针
但是 _Ref_count_base *_Rep 是什么东西呢,很明显就是引用计数。为什么要用指针呢,因为拥有相同_Ptr值的智能指针要拥有同一个引用计数,因此 _Rep 必须为指针。我们把引用计数类_Ref_count_base 放到后面去讨论。
我们继续看一下shared_ptr的
源码可以发现shared_ptr没有显式调用_Ptr_base的构造函数,这意味着shared_ptr只调用_Ptr_base的默认构造函数,但是
shared_ptr的构造函数里大量的调用了两个函数 _Resetp 和 _Reset。
------------------------------------------------------------ _Ptr_base的构造函数 -------------------------------------------------------------------
我们先看一下_Ptr_base的构造函数
复制代码
_Ptr_base()
: _Ptr(0), _Rep(0)
{ // construct
}
_Ptr_base(_Myt&