boost学习之boost::shared_ptr
Boost智能指針——shared_ptr
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釋放其所占的內存。
上面的那個例子可以的圖示如下:
sp1對implementation對象進行管理,其引用計數為1?
增加sp2對implementation對象進行管理,其引用計數增加為2?
sp1釋放對implementation對象進行管理,其引用計數變為1?
sp2釋放對implementation對象進行管理,其引用計數變為0,該對象被自動刪除?
boost::shared_ptr的特點:
和前面介紹的boost::scoped_ptr相比,boost::shared_ptr可以共享對象的所有權,因此其使用范圍基本上沒有什么限制(還是有一些需要遵循的使用規則,下文中介紹),自然也可以使用在stl的容器中。另外它還是線程安全的,這點在多線程程序中也非常重要。
boost::shared_ptr的使用規則:
boost::shared_ptr并不是絕對安全,下面幾條規則能使我們更加安全的使用boost::shared_ptr:
避免對shared_ptr所管理的對象的直接內存管理操作,以免造成該對象的重釋放
shared_ptr并不能對循環引用的對象內存自動管理(這點是其它各種引用計數管理內存方式的通病)。
不要構造一個臨時的shared_ptr作為函數的參數。
如下列代碼則可能導致內存泄漏:
void?test()
{
????foo(boost::shared_ptr<implementation>(new????implementation()),g());
}
正確的用法為:
void?test()
{
????boost::shared_ptr<implementation> sp????(new?implementation());
????foo(sp,g());
}
轉載:https://blog.csdn.net/maweiqi/article/details/7889397?utm_source=copy
總結
以上是生活随笔為你收集整理的boost学习之boost::shared_ptr的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 年龄、性别2022 cnn算法笔记
- 下一篇: linux系统如何备份系统软件,Linu