Boost智能指標——shared_ptr

來源:互聯網
上載者:User

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\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());
    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.