C++11智能指针(五)

2014-11-24 11:29:00 · 作者: · 浏览: 3
候)会调用第一个函数。
这里我简单描述一下_Do_enable的作用:
因为_Ty继承于enable_shared_from_this(实际上_Ty::_EStype就是_Ty,有兴趣的朋友可以去看一下 enable_shared_from_this的源码),enable_shared_from_this内部保存着一个weak_ptr<_Ty>的弱指针,而_Do_enable的作用就是更新一下这个弱指针的值(使用过shared_ptr的朋友都应该知道enable_shared_from_this是用于共享this指针,而这个共享this指针的操作就是通过这个weak_ptr达到的)。
------------------------------------------------------------ shared_ptr的构造函数 -------------------------------------------------------------
接着我们看一下shared_ptr的调用了_reset的构造函数
复制代码
1 shared_ptr(const _Myt& _Other) _NOEXCEPT
2 { // construct shared_ptr object that owns same resource as _Other
3 this->_Reset(_Other);
4 }
5
6 template
7 shared_ptr(const shared_ptr<_Ty2>& _Other,
8 typename enable_if::value,
9 void>::type ** = 0) _NOEXCEPT
10 { // construct shared_ptr object that owns same resource as _Other
11 this->_Reset(_Other);
12 }
13
14 template
15 explicit shared_ptr(const weak_ptr<_Ty2>& _Other,
16 bool _Throw = true)
17 { // construct shared_ptr object that owns resource *_Other
18 this->_Reset(_Other, _Throw);
19 }
20
21 template
22 shared_ptr(auto_ptr<_Ty2>&& _Other)
23 { // construct shared_ptr object that owns *_Other.get()
24 this->_Reset(_STD move(_Other));
25 }
26
27 template
28 shared_ptr(const shared_ptr<_Ty2>& _Other, const _Static_tag& _Tag)
29 { // construct shared_ptr object for static_pointer_cast
30 this->_Reset(_Other, _Tag);
31 }
32
33 template
34 shared_ptr(const shared_ptr<_Ty2>& _Other, const _Const_tag& _Tag)
35 { // construct shared_ptr object for const_pointer_cast
36 this->_Reset(_Other, _Tag);
37 }
38
39 template
40 shared_ptr(const shared_ptr<_Ty2>& _Other, const _Dynamic_tag& _Tag)
41 { // construct shared_ptr object for dynamic_pointer_cast
42 this->_Reset(_Other, _Tag);
43 }
复制代码
这里又用到了模板的最特化匹配,注意L1 - L12
  is_convertible<_Ty2 *, _Ty *>::value
C++11提供的一个类型测试模板,用于测试_Ty2 * 与 _Ty *之间是否有合法转换。当有的时候将调用函数L6 - L12,否则调用L1 - L4
这也是shared_ptr<_Ty>可以向shared_ptr<_Ty的父类>向上转型的秘密。