欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C++中Boost的智能指針shared_ptr

 更新時(shí)間:2022年07月05日 09:35:35   作者:天方  
這篇文章介紹了C++中Boost的智能指針shared_ptr,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

boost::scoped_ptr雖然簡(jiǎn)單易用,但它不能共享所有權(quán)的特性卻大大限制了其使用范圍,而boost::shared_ptr可以解決這一局限。顧名思義,boost::shared_ptr是可以共享所有權(quán)的智能指針,首先讓我們通過一個(gè)例子看看它的基本用法:

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

該程序的輸出結(jié)果如下:

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同時(shí)擁有了implementation對(duì)象的訪問權(quán)限,且當(dāng)sp1和sp2都釋放對(duì)該對(duì)象的所有權(quán)時(shí),其所管理的的對(duì)象的內(nèi)存才被自動(dòng)釋放。在共享對(duì)象的訪問權(quán)限同時(shí),也實(shí)現(xiàn)了其內(nèi)存的自動(dòng)管理。

boost::shared_ptr的內(nèi)存管理機(jī)制:

boost::shared_ptr的管理機(jī)制其實(shí)并不復(fù)雜,就是對(duì)所管理的對(duì)象進(jìn)行了引用計(jì)數(shù),當(dāng)新增一個(gè)boost::shared_ptr對(duì)該對(duì)象進(jìn)行管理時(shí),就將該對(duì)象的引用計(jì)數(shù)加一;減少一個(gè)boost::shared_ptr對(duì)該對(duì)象進(jìn)行管理時(shí),就將該對(duì)象的引用計(jì)數(shù)減一,如果該對(duì)象的引用計(jì)數(shù)為0的時(shí)候,說明沒有任何指針對(duì)其管理,才調(diào)用delete釋放其所占的內(nèi)存。

上面的那個(gè)例子可以的圖示如下:

  • sp1對(duì)implementation對(duì)象進(jìn)行管理,其引用計(jì)數(shù)為1

  • 增加sp2對(duì)implementation對(duì)象進(jìn)行管理,其引用計(jì)數(shù)增加為2

  • sp1釋放對(duì)implementation對(duì)象進(jìn)行管理,其引用計(jì)數(shù)變?yōu)?

  • sp2釋放對(duì)implementation對(duì)象進(jìn)行管理,其引用計(jì)數(shù)變?yōu)?,該對(duì)象被自動(dòng)刪除

boost::shared_ptr的特點(diǎn):

和前面介紹的boost::scoped_ptr相比,boost::shared_ptr可以共享對(duì)象的所有權(quán),因此其使用范圍基本上沒有什么限制(還是有一些需要遵循的使用規(guī)則,下文中介紹),自然也可以使用在stl的容器中。另外它還是線程安全的,這點(diǎn)在多線程程序中也非常重要。

boost::shared_ptr的使用規(guī)則:

boost::shared_ptr并不是絕對(duì)安全,下面幾條規(guī)則能使我們更加安全的使用boost::shared_ptr:

  • 避免對(duì)shared_ptr所管理的對(duì)象的直接內(nèi)存管理操作,以免造成該對(duì)象的重釋放

  • shared_ptr并不能對(duì)循環(huán)引用的對(duì)象內(nèi)存自動(dòng)管理(這點(diǎn)是其它各種引用計(jì)數(shù)管理內(nèi)存方式的通?。?。

  • 不要構(gòu)造一個(gè)臨時(shí)的shared_ptr作為函數(shù)的參數(shù)。

如下列代碼則可能導(dǎo)致內(nèi)存泄漏:

void test()
{
    foo(boost::shared_ptr<implementation>(new    implementation()),g());
}

正確的用法為:

void test()
{
    boost::shared_ptr<implementation> sp    (new implementation());
    foo(sp,g());
}

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論