zoukankan      html  css  js  c++  java
  • C++ 智能指针 C++11

    一、缘起

    C++ 语言没有自动内存回收机制,每次 new 出来的内存都要手动 delete。

    程序员忘记 delete,流程太复杂,最终导致没有 delete;

    异常导致程序过早退出,没有执行 delete 的情况并不罕见。

    用智能指针便可以有效缓解这类问题,本文主要讲解参见的智能指针的用法。

    包括:std::auto_ptrstd::shared_ptrstd::weak_ptr、 std::unique_ptr你可能会想,如此多的智能指针就为了解决new、delete匹配问题,真的有必要吗?看文章。

      

    二、具体使用

    1、总括

    对于编译器来说,智能指针 实际上是一个 栈对象,并非指针类型,在栈对象生命期即将结束时,智能指针 通过 析构函数(智能指针的) 释放由它管理的堆内存

    所有智能指针都重载了 “operator->” 操作符,直接返回对象的引用,用以操作对象。访问 智能指针 原来的方法则使用 “.”操作符

    访问智能指针包含的 裸指针 则可以用 get() 函数。

    由于智能指针是一个对象,所以 if (my_smart_object) 永远为真,要判断 智能指针的裸指针是否为空,需要这样判断:if (my_smart_object.get())。

    智能指针包含了 reset() 方法,如果不传递参数(或者传递 NULL),则智能指针会释放当前管理的内存。如果传递一个对象,则智能指针会释放当前对象,来管理新传入的对象。

    悬空指针(Dangling Pointer)指的是:一个指针的指向对象已被删除,那么就成了悬空指针

    我们编写一个测试类来辅助分析:

     1 class Simple {
     2  public:
     3   Simple(int param = 0) {
     4     number = param;
     5     std::cout << "Simple: " << number << std::endl;  
     6   }
     7 
     8   ~Simple() {
     9     std::cout << "~Simple: " << number << std::endl;
    10   }
    11 
    12   void PrintSomething() {
    13     std::cout << "PrintSomething: " << info_extend.c_str() << std::endl;
    14   }
    15   std::string info_extend;
    16   int number;
    17 };

    2、std::auto_ptr

    std::auto_ptr 属于 STL,当然在 namespace std 中,包含头文件 #include<memory> 便可以使用。std::auto_ptr 能够方便的管理单个堆内存对象。

    我们从代码开始分析:

     1 class Simple {
     2  public:
     3   Simple(int param = 0) {
     4     number = param;
     5     std::cout << "Simple: " << number << std::endl;  
     6   }
     7 
     8   ~Simple() {
     9     std::cout << "~Simple: " << number << std::endl;
    10   }
    11 
    12   void PrintSomething() {
    13     std::cout << "PrintSomething: " << info_extend.c_str() << std::endl;
    14   }
    15   std::string info_extend;
    16   int number;
    17 };
     1 void TestAutoPtr() {
     2 
     3 std::auto_ptr<Simple> my_memory(new Simple(1));   // 创建对象,输出:Simple:1
     4 if (my_memory.get()) {  // 判断智能指针是否为空
     5     my_memory->PrintSomething();     // 使用 operator-> 调用智能指针对象中的函数
     6 my_memory.get()->info_extend = "Addition";      // 使用 get() 返回裸指针,然后给内部对象赋值
     7 my_memory->PrintSomething();     // 再次打印,表明上述赋值成功
     8 (*my_memory).info_extend += " other";       // 使用 operator* 返回智能指针内部对象,然后用“.”调用智能指针对象中的函数
     9 my_memory->PrintSomething();       // 再次打印,表明上述赋值成功
    10   }
    11 }       // my_memory 栈对象即将结束生命期,析构堆对象 Simple(1

    执行结果为:

    Simple: 1

    PrintSomething:

    PrintSomething: Addition

    PrintSomething: Addition other

    ~Simple: 1

    上述为正常使用 std::auto_ptr 的代码,一切似乎都良好,不用显式调用 delete函数,智能指针 通过 析构函数 释放由它管理的堆内存

    其实好景不长,我们看看如下的另一个例子:

     1 void TestAutoPtr2() {
     2 
     3   std::auto_ptr<Simple> my_memory(new Simple(1));
     4   if (my_memory.get()) {
     5     std::auto_ptr<Simple> my_memory2;   // 创建一个新的 my_memory2 对象
     6     my_memory2 = my_memory;        // 复制旧的 my_memory 给 my_memory2,my_memory2 完全夺取了 my_memory 的内存管理所有权,
                           // 导致 my_memory 悬空,最后使用时导致崩溃。
    7 my_memory2->PrintSomething(); // 输出信息,复制成功 8 my_memory->PrintSomething(); // 崩溃 9 10 } 11 }

    最终如上代码导致崩溃,如上代码时绝对符合 C++ 编程思想的,居然崩溃了,跟进 std::auto_ptr 的源码后,我们看到,罪魁祸首是“my_memory2 = my_memory”,这行代码,my_memory2 完全夺取了 my_memory 的内存管理所有权,导致 my_memory 悬空,最后使用时导致崩溃

    所以,使用 std::auto_ptr 时,绝对不能使用“operator=”操作符 (因为内存管理所有权会转移

    看完 std::auto_ptr 好景不长的第一个例子后,让我们再来看一个:

    1 void TestAutoPtr3() {
    2   std::auto_ptr<Simple> my_memory(new Simple(1));
    3 
    4       if (my_memory.get()) {
    5         my_memory.release();
    6       }
    7 
    8 }

    执行结果为:

    Simple: 1

    看到什么异常了吗?我们创建出来的对象没有被析构,没有输出“~Simple: 1”,导致内存泄漏

    正确的代码应该为:

     1 void TestAutoPtr3() {
     2 
     3   std::auto_ptr<Simple> my_memory(new Simple(1));
     4   if (my_memory.get()) {
     5     Simple* temp_memory = my_memory.release();
     6     delete temp_memory;
     7   }
     8 }
     9 10 void TestAutoPtr3() {
    11 
    12   std::auto_ptr<Simple> my_memory(new Simple(1));
    13   if (my_memory.get()) {
    14     my_memory.reset();  // 释放 my_memory 内部管理的内存
    15   }
    16 }

    原来 std::auto_ptr 的 release() 函数只是让出内存所有权

    总结:std::auto_ptr 可用来管理单个对象的对内存,但是,请注意如下几点:

    (1)    尽量不要使用“operator=”。如果使用了,请不要再使用先前对象,因为内存管理所有权转移给了新对象

    (2)    记住 release() 函数不会释放对象,仅仅归还所有权

    (3)    std::auto_ptr 最好不要当成参数传递(自行写代码确定为什么不能)。

    (4)    由于 std::auto_ptr 的“operator=”问题,有其管理的对象不能放入 std::vector 等容器中

    使用一个 std::auto_ptr 的限制还真多,还不能用来管理堆内存数组。

    由于 std::auto_ptr 引发了诸多问题,一些设计并不是非常符合 C++ 编程思想,所以引发了下面 boost 的智能指针,boost 智能指针可以解决如上问题。

    让我们继续向下看。

    3、std::shared_ptr

    boost::shared_ptr ,定义在 std 中,包含头文件 #include<memory> 便可以使用。在上面我们看到 boost::scoped_ptr 独享所有权,不允许赋值、拷贝,std::shared_ptr 是专门用于共享所有权的,由于要共享所有权,其在内部使用了引用计数。std::shared_ptr 也是用于管理单个堆内存对象的。

    我们还是从代码开始分析:

     1 class Simple {
     2  public:
     3   Simple(int param = 0) {
     4     number = param;
     5     std::cout << "Simple: " << number << std::endl;  
     6   }
     7 
     8   ~Simple() {
     9     std::cout << "~Simple: " << number << std::endl;
    10   }
    11 
    12   void PrintSomething() {
    13     std::cout << "PrintSomething: " << info_extend.c_str() << std::endl;
    14   }
    15   std::string info_extend;
    16   int number;
    17 };
     1 void TestSharedPtr(std::shared_ptr<Simple> memory) {  // 注意:无需使用 reference (或 const reference)
     2   memory->PrintSomething();
     3   std::cout << "TestSharedPtr UseCount: " << memory.use_count() << std::endl;
     4 
     5 }
     6 
     7 void TestSharedPtr2() {
     8   std::shared_ptr<Simple> my_memory(new Simple(1));
     9   if (my_memory.get()) {
    10     my_memory->PrintSomething();
    11     my_memory.get()->info_extend = "Addition";
    12     my_memory->PrintSomething();
    13     (*my_memory).info_extend += " other";
    14     my_memory->PrintSomething();
    15   }
    16   std::cout << "TestSharedPtr2 UseCount: " << my_memory.use_count() << std::endl;
    17   TestSharedPtr(my_memory);
    18   std::cout << "TestSharedPtr2 UseCount: " << my_memory.use_count() << std::endl;
    19   //my_memory.release();// 编译 error: 同样,shared_ptr 也没有 release 函数
    20 }

    执行结果为:

    Simple: 1

    PrintSomething:

    PrintSomething: Addition

    PrintSomething: Addition other

    TestSharedPtr2 UseCount: 1

    PrintSomething: Addition other

    TestSharedPtr UseCount: 2

    TestSharedPtr2 UseCount: 1

    ~Simple: 1

    std::shared_ptr 也可以很方便的使用。并且没有 release() 函数。关键的一点,std::shared_ptr 内部维护了一个引用计数,由此可以支持复制、参数传递等。std::shared_ptr 提供了一个函数 use_count() ,此函数返回 boost::shared_ptr 内部的引用计数。查看执行结果,我们可以看到在 TestSharedPtr2 函数中,引用计数为 1,传递参数后(此处进行了一次复制),在函数TestSharedPtr 内部,引用计数为2,在 TestSharedPtr 返回后,引用计数又降低为 1。当我们需要使用一个共享对象的时候,std::shared_ptr 是再好不过的了。

    在此,我们已经看完单个对象的智能指针管理,关于智能指针管理数组,我们接下来讲到。

    4、std::weak_ptr

    std::weak_ptr 属于std库,包含头文件 #include<memory> 便可以使用。

    在讲 std::weak_ptr 之前,让我们先回顾一下前面讲解的内容。似乎 std::shared_ptr 智能指针就可以解决所有单个对象内存的管理了,这儿还多出一个 std::weak_ptr,是否还有某些情况我们没纳入考虑呢?

    回答:有。首先 std::weak_ptr 是专门为 boost::shared_ptr 而准备的。有时候,我们只关心能否使用对象,并不关心内部的引用计数。std::weak_ptr 是 std::shared_ptr 的观察者(Observer)对象,观察者意味着 std::weak_ptr 只对 std::shared_ptr 进行引用,而不改变其引用计数,当被观察的 std::shared_ptr 失效后,相应的 std::weak_ptr 也相应失效。

    我们还是从代码开始分析:

       

    class Simple {
     public:
      Simple(int param = 0) {
        number = param;
        std::cout << "Simple: " << number << std::endl;  
      }
    
      ~Simple() {
        std::cout << "~Simple: " << number << std::endl;
      }
    
      void PrintSomething() {
        std::cout << "PrintSomething: " << info_extend.c_str() << std::endl;
      }
      std::string info_extend;
      int number;
    };
    1  void TestWeakPtr() {
    2       std::weak_ptr<Simple> my_memory_weak;
    3       std::shared_ptr<Simple> my_memory(new Simple(1));
    4       std::cout << "TestWeakPtr std::shared_ptr UseCount: " << my_memory.use_count() << std::endl;
    5       my_memory_weak = my_memory;
    6       std::cout << "TestWeakPtr std::shared_ptr UseCount: " << my_memory.use_count() << std::endl;
    7 }

    执行结果为:

    Simple: 1

    TestWeakPtr std::shared_ptr UseCount: 1

    TestWeakPtr std::shared_ptr UseCount: 1

    ~Simple: 1

        我们看到,尽管被赋值了,内部的引用计数并没有什么变化,当然,读者也可以试试传递参数等其他情况。

        现在要说的问题是,std::weak_ptr 到底有什么作用呢?从上面那个例子看来,似乎没有任何作用,其实 std::weak_ptr 主要用在软件架构设计中,可以在基类(此处的基类并非抽象基类,而是指继承于抽象基类的虚基类)中定义一个 std::weak_ptr,用于指向子类的 std::shared_ptr,这样基类仅仅观察自己的 std::weak_ptr 是否为空就知道子类有没对自己赋值了,而不用影响子类 std::shared_ptr 的引用计数,用以降低复杂度,更好的管理对象。

    5. std::unique_ptr

    std::unique_ptr是一个独享所有权的智能指针,它提供了一种严格语义上的所有权,包括:

               i.  拥有它所指向的对象

               ii.  无法进行复制、赋值操作(例题3)

               iii. 保存指向某个对象的指针,当它本身被删除释放的时候,会使用给定的删除器释放它指向的对象

               iv.  具有移动(std::move)语义,可做为容器元素

     三、总结

    如上讲了这么多智能指针,有必要对这些智能指针做个总结:

    1、在可以使用 boost 库的场合下,拒绝使用 std::auto_ptr,因为其不仅不符合 C++ 编程思想,而且极容易出错[2]。

    2、在对象需要共享的情况下,使用 std::shared_ptr.

    3、在需要访问 std::shared_ptr 对象,而又不想改变其引用计数的情况下,使用 std::weak_ptr,一般常用于软件框架设计中。

    4、最后一点,也是要求最苛刻一点:在你的代码中,不要出现 delete 关键字(或 C 语言的 free 函数),因为可以用智能指针去管理。

    ---------------------------------------

    [1]参见《effective C++》,条款06 。

  • 相关阅读:
    MySQL -- 表联结
    Unittest方法 -- 项目实现自动发送邮件
    Linux工作中常用命令
    Requests方法 -- Token获取操作
    Requests方法 -- 关联用例执行
    Requests方法 -- Blog流程类进行关联
    Requests方法 -- 参数化
    defer和async的区别
    js函数收藏:获取cookie值
    XSHELL使用技巧总结
  • 原文地址:https://www.cnblogs.com/jianhui-Ethan/p/4665907.html
Copyright © 2011-2022 走看看