zoukankan      html  css  js  c++  java
  • Boost智能指针——shared_ptr

    文章来源:http://www.cnblogs.com/Ray-chen/archive/2011/12/15/2289095.html

    boost::scoped_ptr虽然简单易用,但它不能共享所有权的特性却大大限制了其使用范围,而boost::shared_ptr可以解决这一局限。顾名思义,boost::shared_ptr是可以共享所有权的智能指针,首先让我们通过一个例子看看它的基本用法:

    #include <string>
    #include <iostream>
    #include <boost/shared_ptr.hpp>

    class implementation
    {
    public:
        ~implementation() { std::cout <<
    "destroying implementation "; }
        
    void do_something(){ std::cout << "did something "; }
    };

    void test()
    {
        boost::shared_ptr<implementation> sp1(
    new implementation());
        std::cout<<
    "The Samplenow has "<<sp1.use_count()<<" references ";

        boost::shared_ptr<implementation> sp2 = sp1;
        std::cout<<
    "The Samplenow has "<<sp2.use_count()<<" references ";
        
        sp1.reset();
        std::cout<<
    "AfterReset sp1. The Sample now has "<<sp2.use_count()<<" references ";

        sp2.reset();
        std::cout<<
    "AfterReset sp2. ";
    }

    void main()
    {
        test();
    }

    该程序的输出结果如下:

    The Sample nowhas 1 references
    The Sample now has 2 references
    After Reset sp1. The Sample now has 1 references
    destroying implementation
    After Reset sp2.

     

     

     

    #include<string>
    #include <iostream>
    #include <boost/shared_ptr.hpp>
    #include <boost/make_shared.hpp>
    using namespace boost;
    using namespace std;
    class implementation
    {
    public:
     ~implementation() { cout <<"destroying implementation ";}
     void do_something() { cout << "did something "; }
    };

     

    void test()
    {
    /* boost::shared_ptr<implementation> sp1(new implementation());*/
     shared_ptr<implementation> sp1;
     sp1=make_shared<implementation>();
     cout<<"The Sample now has"<<sp1.use_count()<<" references ";
    // 
    //  shared_ptr<implementation> sp2 = sp1;
    //  cout<<"The Sample now has"<<sp2.use_count()<<" references ";
    // 
    //  sp1.reset();
    //  cout<<"After Reset sp1. The Sample now has"<<sp2.use_count()<<" references ";
    // 
    //  sp2.reset();
    //  cout<<"After Reset sp2. ";
    }

     

    int main()
    {
     test();
     cout<<"over!";
    }

     

     

     

    可以看到,boost::shared_ptr指针sp1sp2同时拥有了implementation对象的访问权限,且当sp1sp2都释放对该对象的所有权时,其所管理的的对象的内存才被自动释放。在共享对象的访问权限同时,也实现了其内存的自动管理。

    boost::shared_ptr的内存管理机制:

    boost::shared_ptr的管理机制其实并不复杂,就是对所管理的对象进行了引用计数,当新增一个boost::shared_ptr对该对象进行管理时,就将该对象的引用计数加一;减少一个boost::shared_ptr对该对象进行管理时,就将该对象的引用计数减一,如果该对象的引用计数为0的时候,说明没有任何指针对其管理,才调用delete释放其所占的内存。

    上面的那个例子可以的图示如下:

    1.   sp1implementation对象进行管理,其引用计数为1

    2.   增加sp2implementation对象进行管理,其引用计数增加为2

    3.   sp1释放对implementation对象进行管理,其引用计数变为1

    4.   sp2释放对implementation对象进行管理,其引用计数变为0,该对象被自动删除

    boost::shared_ptr的特点:

    和前面介绍的boost::scoped_ptr相比,boost::shared_ptr可以共享对象的所有权,因此其使用范围基本上没有什么限制(还是有一些需要遵循的使用规则,下文中介绍),自然也可以使用在stl的容器中。另外它还是线程安全的,这点在多线程程序中也非常重要。

    boost::shared_ptr的使用规则:

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

    1.   避免对shared_ptr所管理的对象的直接内存管理操作,以免造成该对象的重释放

    2.   shared_ptr并不能对循环引用的对象内存自动管理(这点是其它各种引用计数管理内存方式的通病)。

    3.   不要构造一个临时的shared_ptr作为函数的参数。
    如下列代码则可能导致内存泄漏:
    void test()
    {
        foo(boost::shared_ptr<implementation>(
    new    implementation()),g());
    }
    正确的用法为:
    void test()
    {
        boost::shared_ptr<implementation>sp    (
    new implementation());
        foo(sp,g());
    }

     

     

     

     

    #include "boost/shared_ptr.hpp"
    #include <vector>
    #include <iostream>
    using namespace std;
    using namespace boost;
    class A 
    {
     public:  virtual void sing()=0;
     protected:  virtual ~A() {};
    };
    class B : public A 
    {
     public:  virtual void sing() 
     {    std::cout << "Do re mi fa sola ";  }
    };
    boost::shared_ptr<A> createA() 
    {  
     boost::shared_ptr<A> p(new B());  return p;
    }
    int main() 
    {   
     vector<boost::shared_ptr<A>> container;  
     for (int i=0;i<10;++i) 
     {    
      container.push_back(createA());  
     }  
     std::cout << "The choir is gathered: ";  
     for (vector<boost::shared_ptr<A>>::iteratorit=container.begin();it!=container.end();++it) 
     {    
      (*it)->sing();  
     }
    }

     

     

     

     

     

     

     

     

     

     

     

     

    shared_ptr是典型的资源获取即初始化技术。不过shared_ptr采用了更复杂一点RAII方式,因为它实现了引用计数。当创建资源的时候将它放入一个shared_ptr, shared_ptr内部记录对这种资源的引用次数为1次。当这个shared_ptr对象离开作用域时,引用次数减1shared_ptr对象析构时,检查到引用次数为0了,就销毁资源:

    {
    boost::shared_ptr<int> pInt(new int(14));
    assert(pInt.use_count() == 1); // new int(14)
    这个指针被引用1
    ...... //
    此处有一系列代码

     

    }   //pInt离开作用域, 所以new int(14)被引用次数为0. 指针被销毁。防止了

     

      此处及以下assert代码都会判断成功。如果......跳出异常。那么pInt也离开了作用域,指针照常还是被销毁,所以智能指针可以有效防止资源泄露。

     

    考虑更多次的引用情况:

     

    {

     

    boost::shared_ptr<int>pInt2;
    assert(pInt2.use_count() == 0);   // temp2
    还没有引用指针

     

    {

     

       boost::shared_ptr<int> pInt1(new int(14));
        assert(pInt1.use_count() == 1); // new int(14)
    这个指针被引用1

     

       pInt2 = pInt1;
        assert(pInt1.use_count() == 2); // new int(14)
    这个指针被引用2
        assert(pInt2.use_count() == 2);
    } //pInt1
    离开作用域, 所以new int(14)被引用次数-1

     

    assert(pInt2.use_count()== 1);
    } // pInt2
    离开作用域,引用次数-1,现在new int(14)被引用0次,所以销毁它

     

    不管资源曾经被多少次引用。当它被引用0次时就会销毁。

     

    1.3

     

      在shard_ptr使用中经常会发现,一个对象会有两次被析构的情况。其实这种是因为那个对象指针被两次当成shard_ptr构造函数里的参数。一定要避免这种现象。考虑如下代码:

     

    {
    int* pInt = new int(14);
    boost::shared_ptr<int> temp1(pInt);
    assert(temp1.use_count() == 1);      //
    用一个指针初始化temp1temp1认为pInt只被它拥有。所以这个指针被引用1

     

    boost::shared_ptr<int>temp2(pInt); // 用一个指针初始化temp2temp2认为pInt只被它拥有。所以这个指针被引用1
    assert(temp2.use_count() == 1);

     

    }   //temp1,temp2都离开作用域,它们都销毁pInt. pInt被销毁了两次!系统终于崩溃了 -_-

     


    正确的做法是将原始指针赋给智能指针后,以后的操作都要针对智能指针了.

     

    {
    boost::shared_ptr<int> temp1(new int(14)); //
    资源获取即初始化
    assert(temp1.use_count() == 1);

     

    boost::shared_ptr<int>temp2(temp1);
    assert(temp2.use_count() == 2);

     

    }   //temp1,temp2都离开作用域,引用次数变为0,指针被销毁

     

    1.4
    如果资源的创建销毁不是以newdelete的方式创建销毁怎么办?shared_ptr也可以指定删除器:

     

    // FileCloser.hFileCloser删除器  
    class FileCloser
    {
    public:
    void operator()(FILE *pf)
    {
        if (pf)
        {
          fclose(pf);
        }
    }
    };

     

    // 某实现文件
    {
    boost::shared_ptr<FILE> fp(fopen(pszConfigFile, "r"),FileCloser());    //
    指定调用FileCloser函数对象销毁资源
    }

     


    1.5
    shared_ptr已经被即将到来的标准库技术报告所采纳,将成为tr1中的一员。为了以后更好的移植现有代码到C++新标准中。可以使用一个namespace的一个小技巧,在头文件StdAfx.h中声明(参考

     

    Effective C++Item 54)
    namespace std

     

    {

     

    namespace tr1 =::boost;           //namespace std::tr1 is an alias

     

    }                                  // for namespace boost

     

    这样就可以用如下方法写代码:

     

    std::tr1::shared_ptr<int>pInt(new int(14));

     

     

     

     

     

     

     

     

     

     

     

    #include<iostream>
    #include <memory>
    #include <boost/shared_ptr.hpp>
     
    using namespace boost;
    using std::cout;
    using std::endl;
    using std::auto_ptr;
     
    class A
    {
        public:
        void print()
        {
           cout<<"hello"<<endl;
        }
    };

    int main()
    {
     auto_ptr<A> aptr1(new A);
        auto_ptr<A> aptr2;
     
        aptr2 = aptr1;
        aptr2->print(); //Ok
        cout<<"pointer in aptr1 is:"<<aptr1.get()<<endl;
        aptr1->print(); //Wrong!
        
        A  *a = new A;
        shared_ptr<A> sptr1(a);
        shared_ptr<A> sptr2(sptr1); //alright
        sptr2 = sptr1;
        sptr2->print(); //ok
        sptr1->print(); //ok
     
        int *b = new int;
        shared_ptr<int> sptr3(b);
        shared_ptr<int> sptr4(b); //WRONG!!
        return 0;
    }

     

     

     

     

     

     

     

     

     

     

    总结

    引用计数智能指针是非常重要的工具。Boost shared_ptr 提供了坚固而灵活的解决方案,它已被广泛用于多种环境下。需要在使用者之间共享对象是常见的,而且通常没有办法通知使用者何时删除对象是安全的。shared_ptr 让使用者无需知道也在使用共享对象的其它对象,并让它们无需担心在没有对象引用时的资源释放。这对于Boost的智能指针类而言是最重要的。你会看到Boost.Smart_ptr中还有其它的智能指针,但这一个肯定是你最想要的。通过使用定制删除器,几乎所有资源类型都可以存入 shared_ptr。这使得shared_ptr 成为处理资源管理的通用类,而不仅仅是处理动态分配对象。与裸指针相比,shared_ptr会有一点点额外的空间代价。我还没有发现由于这些代价太大而需要另外寻找一个解决方案的情形。不要去创建你自己的引用计数智能指针类。没有比使用 shared_ptr智能指针更好的了。

    在以下情况时使用 shared_ptr 

    ·  当有多个使用者使用同一个对象,而没有一个明显的拥有者时

    ·  当要把指针存入标准库容器时

    ·  当要传送对象到库或从库获取对象,而没有明确的所有权时

    ·  当管理一些需要特殊清除方式的资源时[9]

    [9] 通过定制删除器的帮助。

     

     

     

     

     

     

     

     

     

     

     

     

     

     


    int main()
    {
    //  test();
    //  cout<<"over!";
     {
      int* pInt = new int(14);
      boost::shared_ptr<int> temp1(pInt);
      assert(temp1.use_count() == 1);      //
    用一个指针初始化temp1temp1认为pInt只被它拥有。所以这个指针被引用1

     

      boost::shared_ptr<int>temp2(pInt); // 用一个指针初始化temp2temp2认为pInt只被它拥有。所以这个指针被引用1
      assert(temp2.use_count() == 1);

     

     }  // temp1,temp2都离开作用域,它们都销毁pInt. pInt被销毁了两次!系统终于崩溃了 -_-

     


    }

  • 相关阅读:
    jQuery动态表格插件 AppendGrid
    JavaScript:用JS实现加载页面前弹出模态框
    JavaScript(select onchange)的网页跳转的简单实现
    jQuery DataTables的简单实现
    JavaScript 设计模式之命令模式
    JavaScript 设计模式之代理模式
    JavaScript 设计模式之工厂模式
    JavaScript 设计模式之建造者模式
    集群服务器消息通讯办法
    游戏服务器端开发的基本大纲
  • 原文地址:https://www.cnblogs.com/SunkingYang/p/11049249.html
Copyright © 2011-2022 走看看