zoukankan      html  css  js  c++  java
  • 聊聊智能指针 auto_ptr、shared_ptr、weak_ptr和unique_ptr

    本文为转载:https://www.cnblogs.com/zeppelin5/p/10083597.html,对作者有些地方做了修正。

    手写代码是理解C++的最好办法,以几个例子说明C++四个智能指针的用法,转载请注明出处。

    一、auto_ptr

      auto_ptr这是C++98标准下的智能指针,现在常常已经被C++标准的其他智能指针取代。它的缺点是在转移所有权后会使运行期不安全。C++11新标准,用unique_ptr来代替auto_ptr原有功能,其用法介绍见第四部分unique_ptr。

     1 #include <iostream>
     2 #include <memory>
     3 #include <string>
     4 using namespace std;
     5 
     6 void main(){
     7     auto_ptr<string> country[5] =
     8     {
     9         auto_ptr<string>(new string("USA")),
    10         auto_ptr<string>(new string("CHN")),
    11         auto_ptr<string>(new string("RUS")),
    12         auto_ptr<string>(new string("FRA")),
    13         auto_ptr<string>(new string("GRB"))
    14     };
    15 
    16     auto_ptr<string> pwin;
    17     pwin = country[2]; //将所有权从country[2]转让给pwin,此时country[2]不再引用该字符串从而变成空指针,在运行到循环时就会崩溃
    18 
    19     for (int i = 0; i < 5; ++i)
    20         cout << *country[i] << endl;//运行到[2]时崩溃,因为country[2]为空
    21     cout << "The best is " << *pwin << endl;
    22 
    23     system("pause");
    24 }

    二、share_ptr

      share_ptr是C++11新添加的智能指针,它限定的资源可以被多个指针共享。

    用法见下例:

     1 #include <iostream>
     2 #include <memory>
     3 #include <string>
     4 using namespace std;
     5 
     6 void fun(){
     7     shared_ptr<string> pa(new string("CHN"));
     8     shared_ptr<string> pb(new string("USA"));
     9     cout << "*pa " << *pa << endl;//CHN
    10     cout << "pa.use_count " << pa.use_count() << endl;//1
    11     cout << "*pb " << *pb << endl;//USA
    12     cout << "pb.use_count " << pb.use_count() << endl;//1
    13 
    14     pa = pb;
    15     cout << *pa << endl;//USA
    16     cout << "pa.use_count " << pa.use_count() << endl;//2:pa和pb指向同一个资源USA了,该资源的计数为2,所以pb、pb都输出2
    17     cout << "pb.use_count " << pb.use_count() << endl;//2
    18 
    19     pa.reset();
    20     pb.reset();
    21     cout << "pa.use_count " << pa.use_count() << endl;//0
    22     cout << "pb.use_count " << pb.use_count() << endl;//0
    23 }
    24 
    25 void main()
    26 {
    27     fun();
    28     system("pause");
    29 }

    与数组相结合应用,见另一个例子:

     1 #include <iostream>
     2 #include <memory>
     3 #include <string>
     4 using namespace std;
     5 
     6 void main(){
     7     shared_ptr<string> country[5] =
     8     {
     9         shared_ptr<string>(new string("USA")),
    10         shared_ptr<string>(new string("CHN")),
    11         shared_ptr<string>(new string("RUS")),
    12         shared_ptr<string>(new string("FRA")),
    13         shared_ptr<string>(new string("GRB"))
    14     };
    15 
    16     shared_ptr<string> pwin;
    17     cout << pwin.use_count() << endl;//输出0
    18     pwin = country[2]; 
    19     /*使用shared_ptr时运行正常,因为shared_ptr采用引用计数,pwin和films[2]都指向同一块内存,
    20     在释放空间时因为事先要判断引用计数值的大小因此不会出现多次删除一个对象的错误。
    21 
    22     从名字share就可以看出了资源可以被多个指针共享,它使用计数机制来表明资源被几个指针共享。
    23     可以通过成员函数use_count()来查看资源的所有者个数。
    24     */
    25     cout << pwin.use_count() << endl;//输出2
    26 
    27     for (int i = 0; i < 5; ++i)
    28         cout << *country[i] << endl;//对比auto_ptr,这里就不会崩溃,正常的输出所有的string字符串。
    29     cout << "The best is " << *pwin << endl;
    30 
    31     system("pause");
    32 }

    三、weak_ptr

      weak_ptr是一种用于解决shared_ptr相互引用时产生死锁问题的智能指针。如果有两个shared_ptr相互引用,那么这两个shared_ptr指针的引用计数永远不会下降为0,资源永远不会释放。weak_ptr是对对象的一种弱引用,它不会增加对象的use_count,weak_ptr和shared_ptr可以相互转化,shared_ptr可以直接赋值给weak_ptr,weak_ptr也可以通过调用lock函数来获得shared_ptr。

      先看一下两个shared_ptr指针互相引用导致的资源释放失败的例子:

     1 #include <iostream>
     2 #include <memory>
     3 #include <string>
     4 using namespace std;
     5 
     6 class B;
     7 class A
     8 {
     9 public:
    10     shared_ptr<B> pb_;
    11     ~A()
    12     {
    13         cout << "A delete
    ";
    14     }
    15 };
    16 class B
    17 {
    18 public:
    19     shared_ptr<A> pa_;
    20     ~B()
    21     {
    22         cout << "B delete
    ";
    23     }
    24 };
    25 
    26 void fun(){
    27     shared_ptr<B> pb(new B());
    28     cout << "pb.use_count " << pb.use_count() << endl;//1
    29     shared_ptr<A> pa(new A());
    30     cout << "pa.use_count " << pa.use_count() << endl;//1
    31 
    32     pb->pa_ = pa;
    33     cout << "pb.use_count " << pb.use_count() << endl;//1
    34     cout << "pa.use_count " << pa.use_count() << endl;//2
    35     pa->pb_ = pb;
    36     cout << "pb.use_count " << pb.use_count() << endl;//2:由于share_ptr是共享资源,所以pb所指向的资源的引用计数也会加1
    37     cout << "pa.use_count " << pa.use_count() << endl;//2
    38 }//程序结束时,没有调用A和B的析构函数
    39 
    40 void main()
    41 {
    42     fun();
    43     system("pause");
    44 }

    而使用weak_ptr:把A中的shared_ptr<B> pb_改为weak_ptr<B> pb_weak,这样改为了弱引用,传递时不会增加pb引用计数use_count()的值,所以最终能够使A、B资源正常释放:

     1 #include <iostream>
     2 #include <memory>
     3 #include <string>
     4 using namespace std;
     5 
     6 class B;
     7 class A
     8 {
     9 public:
    10     weak_ptr<B> pb_weak;
    11     ~A()
    12     {
    13         cout << "A delete
    ";
    14     }
    15 };
    16 class B
    17 {
    18 public:
    19     shared_ptr<A> pa_;
    20     ~B()
    21     {
    22         cout << "B delete
    ";
    23     }
    24     void print(){
    25         cout << "This is B" << endl;
    26     }
    27 };
    28 
    29 void fun(){
    30     shared_ptr<B> pb(new B());
    31     cout << "pb.use_count " << pb.use_count() << endl;//1
    32     shared_ptr<A> pa(new A());
    33     cout << "pa.use_count " << pa.use_count() << endl;//1
    34 
    35     pb->pa_ = pa;
    36     cout << "pb.use_count " << pb.use_count() << endl;//1
    37     cout << "pa.use_count " << pa.use_count() << endl;//2
    38 
    39     pa->pb_weak = pb;
    40     cout << "pb.use_count " << pb.use_count() << endl;//1:弱引用不会增加所指资源的引用计数use_count()的值
    41     cout << "pa.use_count " << pa.use_count() << endl;//2
    42 
    43     shared_ptr<B> p = pa->pb_weak.lock();
    44     p->print();//不能通过weak_ptr直接访问对象的方法,须先转化为shared_ptr
    45     cout << "pb.use_count " << pb.use_count() << endl;//2
    46     cout << "pa.use_count " << pa.use_count() << endl;//2
    47 }//函数结束时,正确的情况下,应该调用A和B的析构函数
    48 
    49 /*资源B的引用计数一直就只有1,当pb析构时,B的计数减一,变为0,B得到释放,
    50 B释放的同时也会使A的计数减一,同时pa自己析构时也会使资源A的计数减一,那么A的计数为0,A得到释放。
    51 */
    52 
    53 void main()
    54 {
    55     fun();
    56     system("pause");
    57 }

    四、unique_ptr

      unique_ptr 是一个独享所有权的智能指针,它提供了严格意义上的所有权。它取代了C++98中的auto_ptr。

    用法和auto_ptr类似,详情见一下代码:

     1 #include <iostream>
     2 #include <memory>
     3 #include <string>
     4 using namespace std;
     5 
     6 unique_ptr<string> fun2(){
     7     return unique_ptr<string>(new string("RUS"));
     8 }
     9 
    10 void fun(){
    11     unique_ptr<string> pa(new string("CHN"));
    12     //unique_ptr没有use_count()方法
    13     unique_ptr<string> pb(new string("USA"));
    14 
    15     pb = move(pa);
    16     //p2=p1;//错误,不能直接用等于号
    17     if (pa == nullptr)
    18         cout << "pa现在为空" << endl;
    19 
    20     cout << "*pb " << *pb << endl;//pb变成了“CHA”
    21 
    22     string* ps = pb.release();//清空当前智能指针所指的资源对象,并返回指针
    23     cout << "*ps " << *ps << endl;//ps变成了“CHA”
    24 
    25     pa.reset(ps);//重置指向另一个对象
    26     cout << "*pa " << *pa << endl;//pa变成了“CHA”
    27 
    28     pb = fun2();//接收函数的返回值可以用等于号,因为使用了移动构造函数
    29     cout << "*pb " << *pb << endl;//pb变成了“RUS”
    30 }
    31 
    32 void main()
    33 {
    34     fun();
    35     system("pause");
    36 }
  • 相关阅读:
    iOS技术框架构和更新版本的技术特性
    iOS第三方常用类库
    查看MySQL系统变量的命令
    解决WIN7下VMWARE虚拟机无法上网问题
    MySQL性能优化的最佳20+条经验
    PHP高效率写法(详解原因)
    google官方建议使用的网站性能测试工具
    ETL工具-KETTLE教程 实例实战4----转换(值映射、列转行,增加常量、增加序列等)
    ETL工具-KETTLE教程实例实战2----环境介绍
    ETL工具-KETTLE教程实例实战1----术语和定义
  • 原文地址:https://www.cnblogs.com/shaonianpi/p/11179873.html
Copyright © 2011-2022 走看看