【Boost】boost库中智能指针——shared_ptr
boost::scoped_ptr雖然簡(jiǎn)單易用,但它不能共享所有權(quán)的特性卻大大限制了其使用范圍,而boost::shared_ptr可以解決這一局限。顧名思義,boost::shared_ptr是可以共享所有權(quán)的智能指針,首先讓我們通過(guò)一個(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ì)象的訪問(wèn)權(quán)限,且當(dāng)sp1和sp2都釋放對(duì)該對(duì)象的所有權(quán)時(shí),其所管理的的對(duì)象的內(nèi)存才被自動(dòng)釋放。在共享對(duì)象的訪問(wèn)權(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í)候,說(shuō)明沒(méi)有任何指針對(duì)其管理,才調(diào)用delete釋放其所占的內(nèi)存。
上面的那個(gè)例子可以的圖示如下:
boost::shared_ptr的特點(diǎn):
和前面介紹的boost::scoped_ptr相比,boost::shared_ptr可以共享對(duì)象的所有權(quán),因此其使用范圍基本上沒(méi)有什么限制(還是有一些需要遵循的使用規(guī)則,下文中介紹),自然也可以使用在stl的容器中。另外它還是線程安全的,這點(diǎn)在多線程程序中也非常重要。
boost::shared_ptr的使用規(guī)則:
boost::shared_ptr并不是絕對(duì)安全,下面幾條規(guī)則能使我們更加安全的使用boost::shared_ptr:
如下列代碼則可能導(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());
}
總結(jié)
以上是生活随笔為你收集整理的【Boost】boost库中智能指针——shared_ptr的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【Boost】boost库中智能指针——
- 下一篇: 【Boost】boost库中智能指针——