你的浏览器版本过低,可能导致网站不能正常访问!
为了你能正常使用网站功能,请使用这些浏览器。

智能指针

[复制链接]
gaosmile 发布时间:2020-11-24 19:56
现代C++之手写智能指针0.回顾
微信图片_20201124195400.jpg
9 \9 Y! i3 O5 P& v- M) _0 l5 p

所有代码还是放在仓库里面,欢迎star!

https://github.com/Light-City/CPlusPlusThings

前面一节编写了一个RAII的例子:
6 U$ {! j; }/ q8 o- r1 s

class shape_wrapper {6 U5 i7 `# k/ g$ C4 `/ C6 h
public:' T$ f$ n/ @) Y9 f, T+ @
    explicit shape_wrapper(- g" A- ]( C+ ], C3 `
            shape* ptr = nullptr)( L7 L6 w+ Z5 l8 S, f& m+ G. L# R, Y) H
            : ptr_(ptr) {}
# a6 I* b' S2 F& S# s    ~shape_wrapper()* H$ Q# y/ }7 g' _/ _
    {
3 a& ^/ o, v: y, s1 [/ h        delete ptr_;3 ]# @& _3 U8 S! g! s# J6 @0 k
    }* m- |1 S- B- Q4 t2 p5 _
    shape* get() const { return ptr_; }
+ E" e0 V* u, D. a; l1 \private:% Y/ i% ?: ~/ p2 |* [' _
    shape* ptr_;) G' ~4 h9 G# s/ G1 F
};$ U9 y$ ^/ g( e) @$ B+ |

这个类可以完成智能指针的最基本的功能:对超出作用域的对象进行释放。但它缺了点东 西:

  • 这个类只适用于 shape 类
  • 该类对象的行为不够像指针
  • 拷贝该类对象会引发程序行为
    & C* p) F3 D4 S  ^% ]$ s, R+ {/ ]
1.手写auto_ptr与scope_ptr

针对"这个类只适用于 shape 类",我们想到了模板,于是改造为:

template <typename  T>* N/ d) L. U/ i7 w6 Y, X! Q+ r
class smater_ptr {
) p# ~4 g* I4 Y' _$ Cpublic:
/ r8 g' r2 `* X* u! L( U7 v    explicit smater_ptr(
& U+ ?" p% ?0 M' D8 o+ W            T* ptr = nullptr)
7 m. h3 J% x" T" Y! n# l5 A            : ptr_(ptr) {}- y7 r3 K9 |. S6 N
    ~smater_ptr()' h" L( q8 l+ M, m' g. ]
    {( z4 ~0 M! P- @% g2 G. t7 Y
        delete ptr_;
5 {* o; t: S" k# n/ S    }: L% W& p; H3 N) v, h- @2 P, ]
    T* get() const { return ptr_; }) v6 O- A2 o" E/ |  R, e6 P
private:& F& u' C* e! e$ p6 @6 K
    T* ptr_;5 g8 K4 s5 z6 v
};
: o& H9 o, ?* t( \3 J

针对"该类对象的行为不够像指针",我们想到了指针的基本操作有*,->,布尔表达式。

于是添加三个成员函数:

template <typename  T>
, ?9 g  a+ \6 p& D4 P1 R) Cclass smater_ptr {
; M0 V/ ^" e) _  G: _6 U+ Opublic:
& O% F! h$ S+ x           ...
" X2 S( [+ e" d( v$ M* j& `    T& operator*() const { return *ptr_; }
! R% W, J( y/ y7 b5 [    T* operator->() const { return ptr_; }0 a. U1 |& O5 }: @1 X! w
    operator bool() const { return ptr_; }) N' v" U/ A! K$ {, p6 }9 |7 B' K  }# d
    ...% O0 g4 ^4 k" V5 ?& w
private:8 q: C- @* `8 W" S, _+ Q( c0 @
    T* ptr_;; w9 ^1 i' q/ ~' X9 U
};
, w, q" o; P) z' R' y, u

针对"拷贝该类对象会引发程序行为",我们想到了拷贝构造和赋值。

现考虑如下调用:

smart_ptr<shape> ptr1{create_shape(shape_type::circle)};
/ k- u, m1 I6 a' jsmart_ptr<shape> ptr2{ptr1};; c0 \9 ^# x3 J1 k* B+ X8 Y3 ^5 W

对于第二行,究竟应当让编译时发生错误,还是可以有一个更合理的行为?我们来逐一检查 一下各种可能性。最简单的情况显然是禁止拷贝。我们可以使用下面的代码:

template <typename T>5 I. a, x/ U1 h* X: f6 Z8 ^! z
class smart_ptr {5 c6 [- c, F# n0 G
    …
  i& ?3 k1 _$ C) i( k" o    smart_ptr(const smart_ptr&)# C) w  H: w' S# e
    = delete;
0 l1 K! |5 m# k2 h    smart_ptr& operator=(const smart_ptr&)
! x6 L) [3 a! l% i$ e: M4 o    = delete;  Y. o2 V# B- j7 u6 [
    …
' e* P- R, @  ^. z2 d};+ h! G- C3 b. }1 v4 w& k5 B; O

当然,也可以设为private。

禁用这两个函数非常简单,但却解决了一种可能出错的情况。否则,smart_ptr<shape> ptr2{ptr1}; 在编译时不会出错,但在运行时却会有未定义行为——由于会对同一内存释放两次,通常情况下会导致程序崩溃。

我们是不是可以考虑在拷贝智能指针时把对象拷贝一份?不行,通常人们不会这么用,因为使用智能指针的目的就是要减少对象的拷贝啊。何况,虽然我们的指针类型是 shape,但实际指向的却应该是 circle 或 triangle 之类的对象。在 C++ 里没有像 Java 的clone 方法这样的约定;一般而言,并没有通用的方法可以通过基类的指针来构造出一个子类的对象来。

那关键点就来了,所有权!,我们可以拷贝时转移指针的所有权!下面实现便是auto_ptr的核心实现:

template<typename T>: F  }/ q( g8 b7 u- \& Y0 G
class auto_ptr {
6 E3 `$ l, H' ppublic:& U5 O8 [' K; P
    explicit auto_ptr(4 {0 U1 u% j% f# `. u7 ?
            T *ptr = nullptr) noexcept
- p/ [% `7 |! L: c4 h# Y            : ptr_(ptr) {}: N) b" Z- z( g  Y2 @" S( N0 f8 k

2 R4 L  m& R" i5 B    ~auto_ptr() noexcept {5 @: _) u4 s" l5 S0 G. \
        delete ptr_;% m4 b0 Y' K% F1 c1 l1 R# z# W* D
    }
& ]5 U: f, G3 M2 M        // 返回值为T&,允许*ptr=10操作$ e% t$ H; @4 `0 [& n5 x" P
    T &operator*() const noexcept { return *ptr_; }
+ A6 _: L* S. Y. i8 f- [$ S% z: q6 Z4 |/ h; t' p* K- r5 `& z
    T *operator->() const noexcept { return ptr_; }
7 n; T* V4 V3 g% x+ O$ \  }" w+ Z6 ?+ H# ?  o$ q: @, K
    operator bool() const noexcept { return ptr_; }& P2 ]. v8 k0 w' C2 f

- M$ P) S: j# y2 Q) t  {    T *get() const noexcept { return ptr_; }
7 N4 z- F3 f1 ^/ A
) O. V2 C- P1 }- ?6 ]3 b+ F    // 拷贝构造,被复制放释放原来指针的所有权,交给复制方+ c4 Y# P7 H1 s/ ^2 G* ~3 O! K' ^
    auto_ptr(auto_ptr &other) noexcept {. L$ s/ z; N7 N4 c3 @+ M; A; u. Y
        ptr_ = other.release();# c, @8 p2 D5 x' I4 e  H2 V
    }
& \% s  C: ~& ^" J; [6 Y; z+ |( @2 i0 g! y
    // copy and swap7 |5 Y: w8 h# X1 @: O- B  x2 v: Z
    auto_ptr &operator=(auto_ptr &rhs) noexcept {
$ ?5 m5 n! V  B4 o5 G- S//        auto_ptr tmp(rhs.release());
1 u% T9 {& S0 z5 {1 ~+ q//        tmp.swap(*this);
) L& c  I; P  Z6 C7 C        // s上述两行等价于下面一行5 t6 n6 b% S3 s, n
        auto_ptr(rhs.release()).swap(*this);
7 }0 L5 w. N9 i8 E- _        return *this;: I& |7 x3 h  w+ F5 y
    }
2 ~: p( g, A3 s5 N: B9 |+ n5 a9 X6 ~7 T. O
    // 原来的指针释放所有权( H) W7 {. g* Y; u! _2 S
    T *release() noexcept {
6 b5 ^+ m1 R1 x        T *ptr = ptr_;
  `: P" b& i4 @+ p        ptr_ = nullptr;
0 j3 A. c" ]0 L, P" s: G3 V        return ptr;5 t' j; v9 d8 Q: g
    }
; C4 o( `( J. x9 i8 ^9 `, u- }7 M& C9 _, S$ k0 Z
    void swap(auto_ptr &rhs) noexcept {
4 {% F4 D4 U+ p        using std::swap;
( u3 s9 z9 q7 N        swap(ptr_, rhs.ptr_);    // 转移指针所有权6 I% _; `! W! a' r5 S) |  A, r$ F3 a
    }
$ L, W' V: w7 S6 d+ m, ^
  Y" _: `" m8 p$ R% T! \( Mprivate:$ f+ T8 O" M0 M+ A3 v
    T *ptr_;8 K8 c% ]+ E6 s0 Q" e
};
7 t9 r8 i/ h' q+ |5 z3 a. D) X, e
template<typename T>
; [! Z' a* G2 qvoid swap(auto_ptr<T> &lhs, auto_ptr<T> &rhs) noexcept {6 h" i/ s/ ^4 w$ T1 x
    lhs.swap(rhs);
: f( m. E3 z1 r- b4 K* g- j}
1 {) a' t9 `: y7 q" l+ X' w2 c7 _: K' ~; T, G+ D! x# a+ z* O2 a
int main() {1 |+ S' f" H6 Z. a4 N  g
    auto_ptr<shape> ptr1{create_shape(shape_type::circle)};& ^, o6 W( G) F
    auto_ptr<shape> ptr2{ptr1};
2 P; R( _, Z# {4 u  D1 r    if (ptr1.get() == nullptr && ptr2.get())
! x2 \& `3 T. K, R. v1 B        cout << "拷贝构造:ptr1释放了所有权,ptr2获得了所有权" << endl;
0 k& M' y- v: v" z    ptr1 = ptr1;2 W2 f5 d1 T9 [2 b

& m8 h, v& a, W' \9 r6 H. U4 h3 V! `    auto_ptr<shape> ptr3{create_shape(shape_type::rectangle)};& {9 P+ D5 C9 q9 @
    ptr1 = ptr3;& S+ t1 W; v8 d4 D( T- B

7 k3 Q/ e' S/ K: g0 {$ m  K    if (ptr3.get() == nullptr && ptr1.get())
8 A4 s4 [- S7 u2 E+ ]7 S+ V! ?        cout << "赋值操作:始终只有一个对象管理一个区块!ptr3释放了所有权,ptr1获得了所有权" << endl;
1 I! B1 J  n2 R6 t}
9 N% ^3 G" E3 Z) u" a3 q8 |

上述通过copy-swap技术完成了避免自我赋值与保证了强异常安全!

如果你觉得这个实现还不错的话,那恭喜你,你达到了 C++ 委员会在 1998 年时的水平:上面给出的语义本质上就是 C++98 的 auto_ptr 的定义。如果你觉得这个实现很别扭的话,也恭喜你,因为 C++ 委员会也是这么觉得的:auto_ptr 在 C++17 时已经被正式从C++ 标准里删除了。

上面会导致什么问题呢?

看一下输出结果:

shape: ^0 }  `1 a9 z8 f% _% \
circle
' g) o: U, n7 S1 G' g拷贝构造:ptr1释放了所有权,ptr2获得了所有权
4 c8 M/ V9 r2 w& ^, X8 G, rshape& K) _3 s0 X8 w
rectangle
, U+ H3 k0 W0 F+ \4 u赋值操作:始终只有一个对象管理一个区块!ptr3释放了所有权,ptr1获得了所有权5 J0 A0 K1 G- E% T! A

shape与circle实在create_shape时候输出的,我们重点关注最后一句话,发现了一个很大的问题:它的行为会让程序员非常容易犯错。一不小心把它传递给另外一个 auto_ptr,你就不再拥有这个对象了。

上述拷贝构造与拷贝赋值分别如下面两张图所示:

微信图片_20201124195412.png
图1
微信图片_20201124195415.png
图2

针对这个问题,在C++11标准出来之前,C++98标准中都一直只有一个智能指针auto_ptr,我们知道,这是一个失败的设计。它的本质是管理权的转移,这有许多问题。而这时就有一群人开始扩展C++标准库的关于智能指针的部分,他们组成了boost社区,他们负责boost库的开发和维护。其目的是为C++程序员提供免费的、同行审查的、可移植的程序库。boost库可以和C++标准库完美的共同工作,并且为其提供扩展功能。现在的C++11标准库的智能指针很大程度上“借鉴”了boost库。

boost::scoped_ptr 属于 boost 库,定义在 namespace boost 中,包含头文件#include<boost/smart_ptr.hpp>可以使用。scoped_ptr 跟 auto_ptr 一样,可以方便的管理单个堆内存对象,特别的是,scoped_ptr 独享所有权,避免了auto_ptr恼人的几个问题。

scoped_ptr是一种简单粗暴的设计,它本质就是防拷贝,避免出现管理权的转移。这是它的最大特点,所以他的拷贝构造函数和赋值运算符重载函数都只是声明而不定义,而且为了防止有的人在类外定义,所以将函数声明为private。但这也是它最大的问题所在,就是不能赋值拷贝,也就是说功能不全。但是这种设计比较高效、简洁。没有 release() 函数,不会导致先前的内存泄露问题。下面我也将模拟实现scoped_ptr的管理机制(实际上就是前面提到的禁止拷贝):

template<class T>2 C" J1 h# h4 ~5 Z' P% L/ h. E6 R
class scoped_ptr // noncopyable% Q6 }7 x  A9 V
{9 [% |- ?2 w: R) c

  U8 v- H6 c2 o9 }! V2 U# Fpublic:4 u+ ?# R* n% g6 ^0 I4 ~7 b
    explicit scoped_ptr(T *ptr = 0) noexcept : ptr_(ptr) {
) S3 Z5 r9 d* H% J' l1 G    }( p! z3 w; G7 n! ~4 d0 G1 h! t
0 u' i: P) ]) a3 E! M- f
    ~scoped_ptr() noexcept {
: g: v* ?* g8 t9 i        delete ptr_;8 Q" o' `  a) S; X: U' F% ^5 H
    }0 X% I& f5 y9 r* I

/ u1 w$ j3 O- x* y    void reset(T *p = 0) noexcept {7 `  ^6 o; W2 a2 R6 d0 `' T
        scoped_ptr(p).swap(*this);
+ s# }( n+ d1 o" u; Q    }, e* D0 X  G( q

. S  N. M1 c# l2 E* l. S- f    T &operator*() const noexcept {' _6 [& a5 T& A! k/ [$ |& x
        return *ptr_;+ j1 Y6 o2 s0 h* }
    }
4 H" V' l) F7 x3 H+ d" v# [3 k2 o  a3 s3 c3 F7 e
    T *operator->() const noexcept {  L# @- J- ~; g1 ~4 [5 _
        return ptr_;, w$ v7 M4 {. W
    }
/ O2 s9 @* D3 I8 r2 l  o" o. n# M
- q9 N9 J& v- i# ^3 a# N+ J5 \) e8 a    T *get() const noexcept {
8 o  P* k2 G9 k4 ]& ]2 c        return ptr_;
) y8 S1 }1 n8 w9 K1 {" p) B    }
% D) s" m5 w$ d, T$ X  d9 G/ L& p/ E* M8 U
    void swap(scoped_ptr &rhs) noexcept {
0 h" |0 p8 b% }        using std::swap;/ C% |" }1 f- J# w/ D
        swap(ptr_, rhs.ptr_);
3 i9 U$ U+ {0 U5 g    }" Y! P" ?- `1 f* h

8 y/ w% Q( L1 B7 Jprivate:
) g# h  ]6 D) e9 A5 i7 K. G; @    T *ptr_;
, A+ Z" R- W. A$ Q, l4 }9 W
; [0 _$ m1 Z" S- Y( m+ S    scoped_ptr(scoped_ptr const &);4 D% t* E+ C$ m* B) m3 K2 K
    scoped_ptr &operator=(scoped_ptr const &);
: P: g: `5 \  u3 D};
4 Q, ]3 U8 _, A# ?( R0 d( S2 Y4 G( M7 f1 J% _
template<typename T>
! X( P. r2 \7 pvoid swap(scoped_ptr<T> &lhs, scoped_ptr<T> &rhs) noexcept {
1 ~$ U7 G5 f( D9 N0 @7 S8 B    lhs.swap(rhs);
- I! \- \4 Z- L+ E9 K* c/ _2 J1 k}
: }9 E" |! i7 \8 Z1 d

scoped_ptr特点总结:

1)与auto_ptr类似,采用栈上的指针去管理堆上的内容,从而使得堆上的对象随着栈上对象销毁时自动删除;

2)scoped_ptr有着更严格的使用限制——不能拷贝,这也意味着scoped_ptr不能转换其所有权,所以它管理的对象不能作为函数的返回值,对象生命周期仅仅局限于一定区间(该指针所在的{}区间,而std::auto_ptr可以);

3)由于防拷贝的特性,使其管理的对象不能共享所有权,这与std::auto_ptr类似,这一特点使该指针简单易用,但也造成了功能的薄弱。

2.手写unique_ptr之子类向基类转换

在上述auto_ptr基础上,我们把拷贝构造与拷贝赋值,改为移动构造与移动赋值。

template<typename T>. B7 ~! E5 V8 b3 H, A
class unique_ptr {) [5 w) U6 S3 G# m8 h# c. ]0 z  K
public:
# \+ }6 R1 g" v! y  [' @( g- Y! G    explicit unique_ptr(
- q& H; `+ K7 L- P  S5 j( O            T *ptr = nullptr) noexcept" b- X; T0 \; @/ @  O. \& l
            : ptr_(ptr) {}4 G3 w, L4 r% @; g. `% G/ ?
, p) ^" t! c0 E+ G
    ~unique_ptr() noexcept {
3 \3 Q+ o) v' u4 g+ A1 C7 D        delete ptr_;
" P/ ?, Z! m* V$ f    }
/ }: v8 v3 ^( z2 n4 z
. L+ l" f8 u. e    T &operator*() const noexcept { return *ptr_; }7 y( M5 X, r  G- [& `3 z+ ]7 V; j# N

* x; O! ~! I; V5 A) T    T *operator->() const noexcept { return ptr_; }
+ T6 N2 L( |5 T; d$ \
; A- n3 K& C2 X; T    operator bool() const noexcept { return ptr_; }, d  ?+ n2 K/ c0 X7 x
( L; x" E3 d# }0 |7 I, R' g
    T *get() const noexcept { return ptr_; }
# ?2 l. N+ L, ]+ `. L6 C, W! _$ H
    unique_ptr(unique_ptr &&other) noexcept {
; f3 u$ y0 }; d- H8 Q, w  X        ptr_ = other.release();/ ~$ M5 y# F$ f# L
    }
& |2 w1 A# H. B( t  u! Y3 f
& b' C+ j; a# ?9 e* H; c    // copy and swap  始终只有一个对象有管理这块空间的权限2 F3 Y) X( _+ I2 U# r
    unique_ptr &operator=(unique_ptr rhs) noexcept {7 `' C$ ], O# C/ w0 g
        rhs.swap(*this);: t  R$ r7 ~) P9 J
        return *this;, \9 y  T, r3 h$ {4 F. O
    }
8 T, L2 I( Y' e
6 p: X" ~7 t% B' r6 Q    // 原来的指针释放所有权4 \; I2 A, C6 n& X" C0 J+ c
    T *release() noexcept {
; i. V& w0 m! @6 R# e9 Z7 C        T *ptr = ptr_;) Z; _7 h' w4 n! f/ E
        ptr_ = nullptr;% X2 ]+ l. v! ~& H8 O% p
        return ptr;! P0 K) o4 s  N
    }
8 T. N6 ]0 B9 ?5 O
9 m: |# x( |9 y* P- E8 [    void swap(unique_ptr &rhs) noexcept {1 e1 g7 P: |3 \5 y0 X" i, J* b1 V
        using std::swap;3 y1 \. }- |2 P2 u0 b
        swap(ptr_, rhs.ptr_);    // 转移指针所有权
2 c+ o" N8 I2 Z3 g/ T' m( S3 y- t    }0 P) E/ C  a- u( F7 X
4 x, n0 J% `* t: S2 @7 A+ O0 C
private:% G0 [- F) Q! F  K; F5 [, V
    T *ptr_;! K& T+ y- r- m. G  y, o0 i
};" k0 q" j+ L" _7 j
template<typename T>
# [3 B2 W7 ]2 l% e3 [3 M- Xvoid swap(unique_ptr<T> &lhs, unique_ptr<T> &rhs) {8 I0 ^' \; Q/ M& M* r' m
    lhs.swap(rhs);
0 u2 o% C' a5 a# N$ e, g}
. m4 ^6 ?, s$ U, n

调用:

int main() {6 i/ r' C3 ]% v4 x
    unique_ptr<shape> ptr1{create_shape(shape_type::circle)};
7 X+ z) v- H3 ?6 I//    unique_ptr<shape> ptr2{ptr1}; // error
9 }" n0 x/ S, Q' }% z* A6 K    unique_ptr<shape> ptr2{std::move(ptr1)};    // ok/ m! d* X( h+ w' ?2 J- x

6 a0 W3 ]0 I( M0 r; P' @    unique_ptr<shape> ptr3{create_shape(shape_type::rectangle)};
, s9 m! T; `- o2 X' o//    ptr1 = ptr3;    // error
# V+ w/ {1 C- x( K  j* c+ h; O    ptr3 = std::move(ptr1); // ok
( @) q" f5 L  O7 u}+ f2 q* q9 q) S

把拷贝构造函数中的参数类型 unique_ptr& 改成了 unique_ptr&&;现在它成了移动构造函数。把赋值函数中的参数类型 unique_ptr& 改成了 unique_ptr,在构造参数时直接生成新的智能指针,从而不再需要在函数体中构造临时对象。现在赋值函数的行为是移动还是拷贝,完全依赖于构造参数时走的是移动构造还是拷贝构造。

最后,一个circle* 是可以隐式转换成 shape*的,但上面的 unique_ptr<circle> 却无法自动转换成 unique_ptr<shape>。

现在我们考虑两种情况:

(1)第一种:当我们只是在原先的移动构造上面添加template <typename U>,此时情况是移动构造变为带模板的移动构造,可以进行子类向基类转换,但是与移动构造相关的,则调用的是默认移动构造,除非是子类向基类转换,才调用带模板的移动构造。

template <typename U>
3 X0 z  U  ], i6 x, Dunique_ptr(unique_ptr<U> &&other) noexcept {2 L; U3 m+ o$ p& p4 \
    ptr_ = other.release();  i& V* ~& g8 q, |
}
( W% e4 a0 X5 K: o; L6 [2 R

六个特殊的成员函数其生成规则如下:

  • 默认构造函数,生成规则和C++98一样,在用户没有声明自定义的构造函数的时候并且编译期需要的时候生成。
  • 析构函数,生成规则和C++98一样,在C++11中有点不同的是,析构函数默认是noexcept。
  • 拷贝构造函数,用户自定义了移动操作会导致不生成默认的拷贝构造函数,其它和C++98的行为一致。
  • 拷贝赋值操作符,用户自定义了移动操作会导致不生成默认的拷贝赋值操作,其它和C++98的行为一致。
  • 移动构造函数和移动赋值操作符,仅仅在没有用户自定义的拷贝操作,移动操作和析构操作的时候才会生成。' H# J2 L% z7 r& v8 k

根据《Effective Modern C++》Item17 P115页提到,当类中含有特殊成员函数变为模板特殊成员函数的时候,此时不满足上述生成规则,也就是针对当前例子来说,编译器会默认生成拷贝构造,所以此时上述main调用里面为error的都可以正常运行!

int main() {
+ G$ Q" K' U  Z" Y0 t  s    unique_ptr<shape> ptr1{create_shape(shape_type::circle)};
: _& l! r, o, h    unique_ptr<shape> ptr2{ptr1}; // 由于带模板的移动构造函数引发编译器会默认生成拷贝构造6 F. P, K# d- o9 C3 R% V
    if (ptr1.get() != nullptr)      // bitwise copy 此时ptr1不为NULL
2 |4 ^3 [: Q) R2 h9 x        ptr2.get()->print();
! T( M4 w% k& i7 Z
8 a! r9 v0 ~6 J    unique_ptr<shape> ptr2_2{std::move(ptr1)};    // 调用的是默认的移动构造,而不是带模板的移动构造 bitwise move+ n3 `  N& A6 x6 d7 l
    if (ptr2_2.get() != nullptr && ptr1.get() != nullptr)   // ptr1 不为空4 w  U/ Q- G! I$ M# C2 E3 {
        ptr2_2.get()->print();( ?# |  S8 I. D/ H

% j' s. `, m8 C% T& _! N/ W    unique_ptr<shape> ptr3{create_shape(shape_type::rectangle)};* Z0 Z! k) }2 b0 q' _
    ptr1 = ptr3;    // ok  根据形参先调用默认拷贝,再调用拷贝赋值7 L8 E) d! U* a+ P: b
    ptr3 = std::move(ptr1); // ok 根据形参先调用默认移动构造,而不是带参数的移动构造,再调用移动赋值
) B8 d4 e" @! A& o+ t  A    unique_ptr<shape> ptr4(std::move(new circle));  // ok 调用带模板的移动构造
, M1 h0 y7 M! ]6 U# s( R; x}
# W3 R* M) j  @3 _

调用与结果如上代码所示。

(2)第二种:移动构造与带模板的移动构造同时存在,可以完成子类向基类的转换,此时是满足上述生成规则,此时不会生成拷贝函数!

int main() {/ D/ c3 f0 u$ _7 }1 K3 z
    unique_ptr<shape> ptr1{create_shape(shape_type::circle)};
0 K% `! x& @; F- @; u/ b//    unique_ptr<shape> ptr2{ptr1}; // error
, T. Z9 ^5 b6 ]# }- ~, S" t* K9 q    unique_ptr<shape> ptr2_2{std::move(ptr1)};    // ok
6 C6 p4 a, k3 U* i7 J% p" r    if (ptr2_2.get() != nullptr && ptr1.get() == nullptr)
7 I9 W3 R0 _+ o1 g7 w        ptr2_2.get()->print();
8 o. m& z8 r0 `. y5 J$ y2 e; U4 n/ C; M* B" E, F! n$ Q5 o
    unique_ptr<shape> ptr3{create_shape(shape_type::rectangle)};
) `* r2 L7 l* I6 A//    ptr1 = ptr3;    // error, z. s# Z) ~2 q6 z" j1 h* g
    ptr3 = std::move(ptr1); // ok
) k! U! s' \% y: a% o& ^" D. j2 Z//    unique_ptr<circle> cl{create_shape(shape_type::circle)};  // error 因为create_shape返回的是shape 不能基类转子类% Q. F# X- I  [; ]; N6 ?* _
    unique_ptr<circle> cl{new circle()};4 U3 L* m* T, t& n7 i
    unique_ptr<shape> ptr5(std::move(cl));  // ok unique<circle>转unique<circle>
3 {: D: e5 x& ]  E0 v) b}- t7 _! i- h2 f- [, j8 ~

小结:

(1)我们需要了解子类向基类的隐式转换,通过将移动构造函数变为带模板的移动构造函数,要明白两者共存情况与只有带模板的移动或者其他构造函数对编译器生成规则的影响!上述代码,此时还不能完成基类向子类的转换!例如:unique_ptr<circle>转unique_ptr<shape>。

(2)auto_ptr与unique_tr都是独占所有权,每次只能被单个对象所拥有,unique_ptr与auto_ptr不同的是使用移动语义来显示的编写。auto_ptr是可以说你随便赋值,但赋值完了之后原来的对象就不知不觉的报废.搞得你莫名其妙。而unique_ptr就干脆不让你可以随便去复制,赋值.如果实在想传个值就哪里,显式的说明内存转移std:move一下。然后这样传值完了之后,之前的对象也同样报废了.只不过整个move你让明显的知道这样操作后会导致之前的unique_ptr对象失效。scope_ptr则是直接不允许拷贝。由于防拷贝的特性,使其管理的对象不能共享所有权。

3.shared_ptr之引用计数

unique_ptr 算是一种较为安全的智能指针了。但是,一个对象只能被单个 unique_ptr所拥有,这显然不能满足所有使用场合的需求。一种常见的情况是,多个智能指针同时拥有一个对象;当它们全部都失效时,这个对象也同时会被删除。这也就是 shared_ptr 了。

两者区别如下:

微信图片_20201124195419.png

多个shared_ptr不仅共享一个对象,同时还得共享同一个计数。当最后一个指向对象(和共享计数)的shared_ptr析构时,它需要删除对象和共享计数。

首先需要一个共享计数的实现:

class shared_count {
" [! O. l$ K  ~, `2 Spublic:+ ^0 S+ a  U. B) J$ _  |% z
    shared_count() : count_(1) {
8 y4 ^" [* f- p8 P: v3 Q, p/ |! h+ Y: M8 i
    }3 j. G. {" g0 E4 Z
# l+ E$ k- Z& Q
    // 增加计数
) x0 r5 K# b% z+ k  j    void add_count() {: c: k% w) v5 s5 }" u8 m, j
        ++count_;
6 q/ Q0 H$ b) V    }
1 @' I% o1 J; e0 E, `/ L4 W3 J, X, @( M9 k5 f/ [+ `6 m: p) C
    // 减少计数
, n5 V" g  N1 q+ D; L1 P0 {/ P    long reduce_count() {
, ]6 j9 |/ r  b6 P; u        return --count_;  i" r' E5 y/ x0 [& A- T
    }& P9 J" E3 D2 y+ @3 b
! Q9 i: O2 z% x/ N$ S
    // 获取当前计数3 U9 X4 O, o: _- n9 x/ e
    long get_count() const {$ g7 _7 @$ N* F( i% C
        return count_;! b% {: S! Q5 {+ S
    }
* H3 c: L6 k7 I( X4 J% r5 d' U
+ ~/ A  O# [- o: U5 h5 @. Vprivate:
  A* D1 N2 C! X  E0 L- e    long count_;
( E/ n' P" `2 v};
' M/ K  G. `2 b' G9 Q4 A

接下来实现引用计数智能指针:

构造与析构、swap实现如下所示:

template<typename T>& X9 u" c# G8 \' ?; _  U! n1 p
class shared_ptr {
7 Y6 p8 D$ Q" o0 H- x, bpublic:
1 n! C. j- R6 D3 ^7 y4 l6 V    explicit shared_ptr(  n& t# d6 t4 ?7 Q. h$ v
            T *ptr = nullptr) noexcept: W. I. x% U, z& L
            : ptr_(ptr) {  ]8 M$ p8 `' V" \3 a
        if (ptr) {& @9 Y9 N. v( e, t% @! k, u
            shared_count_ = new shared_count();
7 Y. O, i8 [  `7 r" q  w! U3 B        }  \- U  X& Z. O4 p& r
    }5 o& [, d2 R; v
1 B" y( Q; m' a: _! ~
    ~shared_ptr() noexcept {
, H# M' o! a0 I. P2 I: @        // 最后一个shared_ptr再去删除对象与共享计数. a3 T7 g* B+ _; u
        // ptr_不为空且此时共享计数减为0的时候,再去删除9 f& B8 v6 b2 {! Q  q
        if(ptr_&&!shared_count_->reduce_count()) {; R* o5 X: u; q( f0 e$ y7 d
            delete ptr_;6 k3 \. _3 U- P( `
            delete shared_count_;
1 O: u! e! u4 J% B4 w( X$ j        }
6 _7 |. R. G& N5 L' e    }
) X4 Q2 ?9 }' T) R9 @3 A, A        : x  A4 z) k9 m2 B
    void swap(shared_ptr &rhs) noexcept {. L# {# H" V) T+ x0 T& v
        using std::swap;
6 M( z1 Z) }; q6 n( Z4 g; y        swap(ptr_, rhs.ptr_);) x- ?# R" Z$ G$ q) \9 K6 y
        swap(shared_count_,rhs.shared_count_);
9 E# t( M8 ~' j! D; R! l8 P" W8 j* a    }
! V6 {) i9 V5 l4 L1 F3 H, y( R8 i  [" f/ a
private:! j, Y% y# ]4 H* A7 Z7 |# i
    T *ptr_;. x8 d8 h& Q- B  A9 S
    shared_count *shared_count_;
0 T* _, V' }/ h* H4 H};
1 B4 K$ T/ `4 ^+ O/ Ftemplate<typename T>
/ N7 I$ q" \/ L! [, ~7 [void swap(shared_ptr<T> &lhs, shared_ptr<T> &rhs) noexcept {
* X  n4 n' Z- r/ {: }$ B. G, c    lhs.swap(rhs);
7 B% W' e4 W4 x  O}
. `# p( E9 b2 y+ p! T5 ?% P

之前的赋值函数,编译器可以根据调用来决定是调拷贝构造还是移动构函数,所以不变:

// copy and swap  始终只有一个对象有管理这块空间的权限
2 h9 S6 ~. V2 Ushared_ptr &operator=(shared_ptr rhs) noexcept {( |0 z9 L0 |+ e$ l8 j) j/ j3 s6 J1 S' p
    rhs.swap(*this);
/ J& V1 \' ]" V4 [  {    return *this;
7 |& [/ Z* P7 s& @+ Y}
$ m! ]8 V" {/ z1 O8 Y& ?

拷贝构造与移动构造需要改变:

除复制指针之外,对于拷贝构造的情况,我们需要在指针非空时把引用数加一,并复制共享 计数的指针。对于移动构造的情况,我们不需要调整引用数,直接把 other.ptr_ 置为 空,认为 other 不再指向该共享对象即可

实现如下所示:

template<typename U>
1 _# @1 Y) l& [& ]shared_ptr(const shared_ptr<T> &other) noexcept {
0 D+ `/ v. Y9 t' ^9 B' i% M- X# I    ptr_ = other.ptr_;  u1 y) @; B- ]; A' e' h" a/ x
    if (ptr_) {6 ]- C$ z; ?: X; r2 A' W
        other.shared_count_->add_count();" ^  Y% r. T( n, E: ?% w- A# d
        shared_count_ = other.shared_count_;7 X! `# |1 t8 ]4 a  K0 R- V
    }
6 R/ r9 V8 ?0 S+ U}+ b2 J' q; @1 u% d! S/ c# V) d
0 a0 p( w4 j, M$ r3 a) X$ a) \$ n
template<typename U>
8 |* m4 S" w8 G- O2 [; a$ g2 ^shared_ptr(shared_ptr<U> &&other) noexcept {( J: P, x% B. h' u" Y
    ptr_ = other.ptr_;
% Z/ a; w: x, o, Y    if (ptr_) {
: d. J+ h2 }# v6 {; D        shared_count_ = other.shared_count_;
/ P5 N8 |; C6 R$ ]/ Q9 d- B, V        other.shared_count_ = nullptr;
3 U; U+ o+ N' N6 C) J8 S' Q    }
0 C. P; g% F8 Q! @, S. C}
5 x7 P: b8 {1 D# a9 c

当运行的时候,报错:

‘circle* shared_ptr<circle>::ptr_’ is private
, V, J# s1 e6 _: v! a; k

错误原因是模板的各个实例间并不天然就有 friend 关系,因而不能互访私有成员 ptr_和shared_count_。我们需要在 smart_ptr 的定义中显式声明:

template<typename U>6 p1 U6 P: T6 A
friend class shared_ptr;
9 ~, Y4 |- h( w9 k

此外,在当前引用计数实现中,我们应该删除release释放所有权函数,编写一个返回引用计数值的函数。

long use_count() const noexcept {% s7 J0 v4 n! ~" W8 B5 E4 B
    if (ptr_) {$ ]4 E- t: {2 e4 G
        return shared_count_->get_count();
' w, D% g1 @7 i+ q    } else {1 V6 E  r' s8 U- H5 Z
        return 0;; Q+ q+ q/ {) o
    }
8 V" M4 k0 f& U% e}
* }$ O+ {5 M4 x/ U+ y+ L

调用:

shared_ptr<circle> ptr1(new circle());5 x8 ]* h/ W2 {4 E2 D( v( m
cout << "use count of ptr1 is " << ptr1.use_count() << endl;
5 s, K/ ?( l9 E" d0 U. q( \shared_ptr<shape> ptr2, ptr3;: s+ H' {/ j5 o( n! g/ E, n' h9 _
cout << "use count of ptr2 was " << ptr2.use_count() << endl;
( l( H4 a6 e& ]6 \$ Y; ~ptr2 = ptr1;        // shared_ptr<circle>隐式转换shared_ptr<shape> 调用带模板的拷贝构造
* R) ]4 @0 k  l' m7 b  |//    cout<<"======="<<endl;
9 L7 ?) J$ E$ c. m0 M5 P2 i//    ptr3 = ptr2;        // 调用的是编译器生成的默认拷贝构造 所以引用计数不会增加 ptr3=ptr2* u1 _. b9 N. u' E$ K8 |9 U' C
//    cout<<"======="<<endl;
( n- k9 x2 X: {( N# I  `ptr3 = ptr1;; H; F; ~! r; G( `3 I% j
cout << "此时3个shared_ptr指向同一个资源" << endl;9 I$ S+ P1 e( `- f* `5 c
cout << "use count of ptr1 is now " << ptr1.use_count() << endl;
/ m) Y8 l3 Y* x' c9 u- E$ T- ocout << "use count of ptr2 is now " << ptr2.use_count() << endl;
* H. {' Y3 ?3 b5 l3 Ecout << "use count of ptr3 is now " << ptr3.use_count() << endl;  f5 E2 A+ M1 f
if (ptr1)
* X  p& g3 p! F) ~    cout << "ptr1 is not empty" << endl;
% Y6 n% J9 t. |5 w* L/ w// 会先调用赋值函数,由编译器决定调用的是拷贝构造还是移动构造,造出一个新的临时对象出来,临时对象会在跳出作用域后被析构掉。
  u+ {1 h; b; e  |5 x+ a// 在析构函数中,会先判断该临时对象的是否指向资源,如果没有,析构结束。否则,对引用计数减1,判断引用计数是否为0,如果为0,删除共享引用计数指针,否则不操作。
) B' Z& g( d7 P1 m/ `cout << "此时2个shared_ptr指向同一个资源" << endl;, G5 Z8 r( g6 x  ?
ptr2 = std::move(ptr1);
5 t6 F/ W. Q4 U1 H. }7 X0 hif (!ptr1 && ptr2) {      // 调用的是bool重载操作符
7 P* W$ z1 G& T! Q3 }* x    cout << "ptr1 move to ptr2" << endl;
% j1 k; e' ]5 {! R/ o( M    cout << "use count of ptr1 is now " << ptr1.use_count() << endl;6 O- ?. P( U; h- f: K" j
    cout << "use count of ptr2 is now " << ptr2.use_count() << endl;" [7 ^' h2 G1 _/ T
    cout << "use count of ptr3 is now " << ptr3.use_count() << endl;6 X. t; |. ]/ o! X6 J
}
6 I  ?) {! M, v+ M

输出:

shape
+ Z7 X9 ]( T# i1 c1 ocircle
" L0 X2 \7 f- ^; N, t: cuse count of ptr1 is 1
+ g( P- ^5 W0 Y% k" tuse count of ptr2 was 0. d/ x& g0 x  M# D
此时3个shared_ptr指向同一个资源
% d' D$ f! ]0 C* H5 Muse count of ptr1 is now 3
& d5 [/ v( h  S8 Luse count of ptr2 is now 3
( B2 W& L1 F0 P; F/ Vuse count of ptr3 is now 3+ R/ {6 Z; }& B  o$ e
ptr1 is not empty
, j3 x6 |" u; V此时2个shared_ptr指向同一个资源
5 g4 M) z& u" t& |4 bptr1 move to ptr2
0 Z1 Y9 }9 I& w$ @) [use count of ptr1 is now 0
7 F* d- J# q. M7 H) K( [use count of ptr2 is now 2
% |5 e$ m2 D3 ruse count of ptr3 is now 28 F5 A9 x8 k) I
~circle/ D& R0 m, J( d- Q& x; Y$ o
~shape
+ r# A& B5 g# ]8 ^% V

有几点注意事项:

  • 上述代码没有考虑线程安全性,这里只是简化版

  • =赋值重载函数不加&,编译器决定调用拷贝构造还是移动构造,来造出一个临时对象出来。

  • 根据前面提到的,当类中特殊函数变为带模板的函数,编译器仍然会生成默认拷贝构造与默认移动构造。


    7 y2 M/ I- e' N8 E6 }& N* R/ i

针对第一点:例如:ptr2 = std::move(ptr1);

会先调用赋值函数,由编译器决定调用的是拷贝构造还是移动构造,造出一个新的临时对象出来,临时对象会在跳出作用域后被析构掉。在析构函数中,会先判断该临时对象的是否指向资源,如果没有,析构结束。否则,对引用计数减1,判断引用计数是否为0,如果为0,删除共享引用计数指针,否则不操作。

针对第二点:

shared_ptr<shape> ptr2, ptr3;
- i/ u0 j9 ^$ ]  ~ptr3 = ptr2;        // 调用的是编译器生成的默认拷贝构造 所以引用计数不会增加
# M7 P) i) H' l7 R& y& L; H

两者都是一种类型,所以在调用赋值操作后,不会调用带模板的拷贝构造来创建临时变量,而是调用编译器生成的默认拷贝构造,所以此时引用计数不会增加。

4.指针类型转换

对应于 C++ 里的不同的类型强制转:

  • dynamic_cast
  • static_cast
  • const_cast
  • reinterpret_cast5 o7 v# E  m8 g8 P' }7 \% c8 ]
4.1 dynamic_cast

在上述unique_ptr处实现了子类向基类的转换,但是却没有实现基类向子类的转换,例如::unique_ptr<circle>转unique_ptr<shape>。

实现这种,需要使用dynamic_cast,实现如下:

首先为了实现这些转换,我们需要添加构造函数,允许在对智能指针内部的指针对象赋值时,使用一个现有的智能指针的共享计数。

// 实现强制类型转换需要的构造函数
/ b! ]' H/ P0 M" X$ u- Y8 `  stemplate<typename U>
* g, w2 u% K" T! ~shared_ptr(const shared_ptr<U> &other, T *ptr) noexcept {
- z3 d+ s+ M* p) N2 v: M7 d    ptr_ = ptr;
* X+ ^5 U; V1 o( i9 V    if (ptr_) {
& O: c9 g  J7 B' ^/ s        other.shared_count_->add_count();
8 ]9 O# @  s: y/ I% A        shared_count_ = other.shared_count_;
/ V3 M# |- o8 j" ~0 Z5 _4 j  V    }
( J/ Z: z) f) r}
0 E! e3 ^3 d# \3 y( }

其次,就是实现转换函数:

template<typename T, typename U>1 I: i9 v5 d( Z/ m
shared_ptr<T> dynamic_pointer_cast(const shared_ptr<U> &other) noexcept {# ^' [, v% M5 y) Z
    T *ptr = dynamic_cast<T *>(other.get());
) M) k! u+ ?) v$ M; m- [8 L3 ~9 D    return shared_ptr<T>(other, ptr);& {1 W  d! b% d, v5 q& R. B
}
% `1 S8 b; S- g2 H0 D

调用:

// shape* -> circle* 使用dynamic_cast转换后,指针为空.此时资源还是被dptr2拥有,dptr1为0
& j( M. Y% ~+ eshared_ptr<shape> dptr2(new shape);
# L+ e/ {" A! m* e, y! Bshared_ptr<circle> dptr1 = dynamic_pointer_cast<circle>(dptr2);      // 基类转子类
  A3 m1 u9 j7 \( G2 l) t
$ _: _9 N* ?! V) fcout << "use count of dptr1 is now " << dptr1.use_count() << endl;    // 0
: `0 Y7 f0 z; R( Ecout << "use count of dptr2 is now " << dptr2.use_count() << endl;    // 1- I0 c9 f" ?, _
7 S( c+ p- L, ~/ ?+ H
// circle* -> circle* 使用dynamic_cast转换后,指针不为空,此时资源被两者共同使用,引用计数为2% U5 Z% M0 U& \0 {8 X
shared_ptr<shape> dptr3(new circle);4 X+ l& B2 m" X3 P; E* C; y
//    shared_ptr<circle> dptr3(new circle);     // 上面或者当前行,后面输出一样!
8 h0 ]: F7 w" gshared_ptr<circle> dptr1_1 = dynamic_pointer_cast<circle>(dptr3);      // 基类转子类+ c4 C% a1 Z0 k' k
+ z" v4 c- y' b8 f8 U
cout << "use count of dptr1_1 is now " << dptr1_1.use_count() << endl;    // 2
# Q3 e( z( [) M& Ocout << "use count of dptr3 is now " << dptr3.use_count() << endl;    // 2
8 A+ G4 o( l; I( o0 E% ^! z* m+ [4 [6 [
// circle* -> circle* 使用dynamic_cast转换后,指针不为空,此时资源被两者共同使用,引用计数为2( h1 T. H3 l3 L! Q# M' {
shared_ptr<circle> dptr3_1(new circle);& z* v7 O- b; D$ c3 Y# Y) z# A
shared_ptr<shape> dptr2_1 = dynamic_pointer_cast<shape>(dptr3_1);      // 子类转基类 上行转换,安全!
2 {* t: w8 Z* `8 s% [" R% Q
; h3 U# [% K! f$ M% Ccout << "use count of dptr2_1 is now " << dptr2_1.use_count() << endl;    // 2$ Z; d" ?1 ^- g: K7 v$ B
cout << "use count of dptr3_1 is now " << dptr3_1.use_count() << endl;    // 24 w0 g: B" c: w* G4 W, K7 V

dynamic_cast主要用于类层次间的上行转换和下行转换,还可以用于类之间的交叉转换。在类层次间进行上行转换时,dynamic_cast和static_cast的效果是一样的;在进行下行转换时,dynamic_cast具有类型检查的功能,比static_cast更安全。在多态类型之间的转换主要使用dynamic_cast,因为类型提供了运行时信息。

(1)下行转换,基类转换为子类,例如:智能指针转换类似于shape* 转换为circle* 使用dynamic_cast转换后,指针为空.此时资源还是被dptr2拥有,dptr1为0。比static_cast安全。

(2)平行转换,指向一致的相互转换,例如:智能指针转换类似于circle*转换为circle*。此时引用计数为两者共享。

(3)上行转换,子类转基类,例如:智能指针转换类似于circle*转换为shape*,此时引用技术为两者共享。等价于static_cast。

4.2 static_cast

同样,编写如下:

template<typename T, typename U>9 m5 q5 k% a: p  x+ ?  a% L$ B
shared_ptr<T> static_pointer_cast(const shared_ptr<U> &other) noexcept {
. {% s. C  n0 _8 L3 d8 k2 N2 F    T *ptr = static_cast<T *>(other.get());8 d* t( g" K9 g/ x6 C
    return shared_ptr<T>(other, ptr);
: R% |, U/ I" Y2 j/ w/ M& l( @}
2 c' @0 }! M- D+ [7 P

调用:

// shape* -> circle* 使用static_cast转换后,指针为空  与dynamic_cast相比,不安全* K/ ]- Y1 ~2 {) \
shared_ptr<shape> sptr2(new shape);! j+ [- w$ w. S) ~; m
shared_ptr<circle> sptr1 = static_pointer_cast<circle>(sptr2);      // 基类转子类
/ |) ~4 q! q% r( B! B
9 C2 O6 }; f& N  o! Lcout << "use count of sptr1 is now " << dptr1.use_count() << endl;    // 08 W- g  f$ y' J+ J# @) g) ]
cout << "use count of sptr2 is now " << dptr2.use_count() << endl;    // 1
+ h$ C0 n2 c" w5 ^& O: m6 i7 p7 I# k. v; N% [' a- e+ s* c
// circle* -> circle* 使用dynamic_cast转换后,指针不为空,此时资源被两者共同使用,引用计数为2$ ]( B- ]) ]5 n7 R8 A
shared_ptr<shape> sptr3(new circle);
4 E/ P0 h* t% b* b4 F( Z" L//    shared_ptr<circle> sptr3(new circle);     // 上面或者当前行,后面输出一样!
5 p7 c" @5 w% {( }7 n- w; tshared_ptr<circle> sptr1_1 = static_pointer_cast<circle>(sptr3);      // 基类转子类
0 X2 x" X. s! {& \% [; F3 a: S& h% p5 S* {, a, @: j
cout << "use count of sptr1_1 is now " << sptr1_1.use_count() << endl;    // 29 V1 k8 P9 n# m" R6 h& Z+ {
cout << "use count of sptr3 is now " << sptr3.use_count() << endl;    // 2
, i0 f4 d, Z9 l' N8 l) T7 P" {" o/ I4 V# }: @
// circle* -> circle* 使用static_cast转换后,指针不为空,此时资源被两者共同使用,引用计数为2 等价于dynamic_cast. j: o. Y/ `6 h3 J% i
shared_ptr<circle> sptr3_1(new circle);) S# n8 B1 q- P; p" R
shared_ptr<shape> sptr2_1 = static_pointer_cast<shape>(sptr3_1);      // 子类转基类 上行转换,安全!( M; _" N" E% y6 n4 N1 F/ W7 i
! v3 ^6 O- \  l4 g) V7 U
cout << "use count of sptr2_1 is now " << sptr2_1.use_count() << endl;    // 2
5 J& f( x- u' y2 T3 c/ K' Q; Ucout << "use count of sptr3_1 is now " << sptr3_1.use_count() << endl;    // 2, L7 E  t; c, }7 _" {

输出结果同上dynamic_cast,不同之处,在下行转换的时候(基类转子类),是不安全的!

4.3 const_cast

去掉const属性:

template<typename T, typename U>
! u6 q# r0 G8 R% B; B! B* }shared_ptr<T> const_pointer_cast(
% l. Q/ d" ^1 ^6 O        const shared_ptr<U> &other) noexcept {# q1 H; C4 W5 s' @1 X+ c5 _9 v. h
    T *ptr = const_cast<T *>(other.get());, O0 w- s5 D9 Z# p+ L5 U$ @7 [( g3 I
    return shared_ptr<T>(other, ptr);
! Q- i7 c# U+ Y6 M}
; I1 X0 u7 C2 f5 ?* I' ?

调用:

shared_ptr<circle> s = const_pointer_cast<circle>(shared_ptr<const circle>(new circle));
: V. V" O1 P' ~2 H* J
4.4 reinterpret_cast

例如:想把一个指针转为整数,就可以用reinterpret_cast。

template<typename T, typename U>
. [: T$ w- N. ~# X7 |shared_ptr<T> reinterpret_pointer_cast(
8 ]4 E+ d& d; ^' b" Q, b6 ]        const shared_ptr<U> &other) noexcept {
( E+ v+ }' |" x- U    T *ptr = reinterpret_cast<T *>(other.get());; m+ ]; }2 t5 C+ I5 n/ A$ [
    return shared_ptr<T>(other, ptr);
3 G$ k$ w% G, c7 B}
1 k( }. b; S, C

调用:

int a = reinterpret_pointer_cast<int>(s);) O5 z: n! Y" i7 ~% X
赞 收藏 1 评论0 发布时间:2020-11-24 19:56

举报

0个回答
关于
我们是谁
投资者关系
意法半导体可持续发展举措
创新与技术
意法半导体官网
联系我们
联系ST分支机构
寻找销售人员和分销渠道
社区
媒体中心
活动与培训
隐私策略
隐私策略
Cookies管理
行使您的权利
官方最新发布
人形机器人运动控制、感知与智能配电
半导体创新技术与应用方向
EE架构与软件定义汽车
12V/48V 汽车智能配电(SPD)
区域控制单元(ZCU)与分区架构
关注我们
st-img 微信公众号
st-img 手机版