shared_ptr 知识汇总

接口:http://zh.cppreference.com/w/cpp/memory/shared_ptr 这个网站比较好,概念比较简洁

如何使用:http://www.cnblogs.com/TianFang/archive/2008/09/19/1294521.html

 

boost::shared_ptr并不是绝对安全,下面几条规则能使我们更加安全的使用boost::shared_ptr:

    1. 避免对shared_ptr所管理的对象的直接内存管理操作,以免造成该对象的重释放
    2. shared_ptr并不能对循环引用的对象内存自动管理(这点是其它各种引用计数管理内存方式的通病)。
    3. 不要构造一个临时的shared_ptr作为函数的参数。
    代码实例
    1. #include "stdafx.h"
      #include <iostream>
      #include <memory>
      using namespace std;
      
      class implementation
      {
      public:
          ~implementation() { std::cout << "destroying implementation\n"; }
          void do_something() { std::cout << "did something\n"; }
      };
      
      void test()
      {
          std::shared_ptr<implementation> sp1(new implementation());
          std::cout << "The Sample now has " << sp1.use_count() << " references\n";
      
          std::shared_ptr<implementation> sp2 = sp1;
          std::cout << "The Sample now has " << sp2.use_count() << " references\n";
      
          sp1.reset();
          std::cout << "After Reset sp1. The Sample now has " << sp2.use_count() << " references\n";
      
          sp2.reset();
          std::cout << "After Reset sp2.\n";
      }
      
      int main()
      {
          test();
      }
posted @ 2016-07-30 14:42  知吾猪  阅读(293)  评论(0编辑  收藏  举报