首页 > 代码库 > 智能指针——shared_ptr

智能指针——shared_ptr

boost::scoped_ptr虽然简单易用,但它不能共享所有权的特性却大大限制了其使用范围,而boost::shared_ptr可以解决这一局限。顾名思义,boost::shared_ptr是可以共享所有权的智能指针

 

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

 

#include <string>#include <iostream>#include <boost/shared_ptr.hpp>class implementation{public:    ~implementation() { std::cout <<"destroying implementation\n"; }    void do_something() { std::cout << "did something\n"; }};void test(){    boost::shared_ptr<implementation> sp1(new implementation());    std::cout<<"The Sample now has "<<sp1.use_count()<<" references\n";    boost::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";}void main(){    test();}该程序的输出结果如下:The Sample now has 1 referencesThe Sample now has 2 referencesAfter Reset sp1. The Sample now has 1 referencesdestroying implementationAfter Reset sp2.

  

智能指针——shared_ptr