1. 程式人生 > >Boost智能指針——shared_ptr

Boost智能指針——shared_ptr

void 內存泄漏 new 其它 let eset 訪問權限 on() 循環引用

#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 references
The Sample now has 2 references
After Reset sp1. The Sample now has 1 references
destroying implementation
After Reset sp2.

可以看到,boost::shared_ptr指針sp1和sp2同時擁有了implementation對象的訪問權限,且當sp1和sp2都釋放對該對象的所有權時,其所管理的的對象的內存才被自動釋放。在共享對象的訪問權限同時,也實現了其內存的自動管理。

boost::shared_ptr的內存管理機制:

boost::shared_ptr的管理機制其實並不復雜,就是對所管理的對象進行了引用計數,當新增一個boost::shared_ptr對該對象進行管理時,就將該對象的引用計數加一;減少一個boost::shared_ptr對該對象進行管理時,就將該對象的引用計數減一,如果該對象的引用計數為0的時候,說明沒有任何指針對其管理,才調用delete釋放其所占的內存。

上面的那個例子可以的圖示如下:

  1. sp1對implementation對象進行管理,其引用計數為1
  2. 增加sp2對implementation對象進行管理,其引用計數增加為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());
    }

Boost智能指針——shared_ptr