淺析Boost智能指針:scoped_ptr shared_ptr weak_ptr
一. scoped_ptr
boost::scoped_ptr和std::auto_ptr非常類似,是一個簡單的智能指針,它能夠保證在離開作用域后對象被自動釋放。下列代碼演示了該指針的基本應(yīng)用:
#include <string>
#include <iostream>
#include <boost/scoped_ptr.hpp>
class implementation
{
public:
~implementation() { std::cout <<"destroying implementation\n"; }
void do_something() { std::cout << "did something\n"; }
};
void test()
{
boost::scoped_ptr<implementation> impl(new implementation());
impl->do_something();
}
void main()
{
std::cout<<"Test Begin ... \n";
test();
std::cout<<"Test End.\n";
}
該代碼的輸出結(jié)果是:
Test Begin ...
did something
destroying implementation
Test End.
可以看到:當(dāng)implementation類離其開impl作用域的時候,會被自動刪除,這樣就會避免由于忘記手動調(diào)用delete而造成內(nèi)存泄漏了。
boost::scoped_ptr特點(diǎn):
boost::scoped_ptr的實(shí)現(xiàn)和std::auto_ptr非常類似,都是利用了一個棧上的對象去管理一個堆上的對象,從而使得堆上的對象隨著棧上的對象銷毀時自動刪除。不同的是,boost::scoped_ptr有著更嚴(yán)格的使用限制——不能拷貝。這就意味著:boost::scoped_ptr指針是不能轉(zhuǎn)換其所有權(quán)的。
1.不能轉(zhuǎn)換所有權(quán)
boost::scoped_ptr所管理的對象生命周期僅僅局限于一個區(qū)間(該指針?biāo)诘?{}"之間),無法傳到區(qū)間之外,這就意味著boost::scoped_ptr對象是不能作為函數(shù)的返回值的(std::auto_ptr可以)。
2.不能共享所有權(quán)
這點(diǎn)和std::auto_ptr類似。這個特點(diǎn)一方面使得該指針簡單易用。另一方面也造成了功能的薄弱——不能用于stl的容器中。
3.不能用于管理數(shù)組對象
由于boost::scoped_ptr是通過delete來刪除所管理對象的,而數(shù)組對象必須通過deletep[]來刪除,因此boost::scoped_ptr是不能管理數(shù)組對象的,如果要管理數(shù)組對象需要使用boost::scoped_array類。
boost::scoped_ptr的常用操作:
可以簡化為如下形式:
namespace boost {
template<typename T> class scoped_ptr : noncopyable {
public:
explicit scoped_ptr(T* p = 0);
~scoped_ptr();
void reset(T* p = 0);
T& operator*() const;
T* operator->() const;
T* get() const;
void swap(scoped_ptr& b);
};
template<typename T>
void swap(scoped_ptr<T> & a, scoped_ptr<T> & b);
}
它的常用操作如下:
成員函數(shù) |
功能 |
operator*() |
以引用的形式訪問所管理的對象的成員 |
operator->() |
以指針的形式訪問所管理的對象的成員 |
get() |
釋放所管理的對象,管理另外一個對象 |
swap(scoped_ptr& b) |
交換兩個boost::scoped_ptr管理的對象 |
下列測試代碼演示了這些功能函數(shù)的基本使用方法。
#include <string>
#include <iostream>
#include <boost/scoped_ptr.hpp>
#include <boost/scoped_array.hpp>
#include <boost/config.hpp>
#include <boost/detail/lightweight_test.hpp>
void test()
{
// test scoped_ptr with a built-in type
long * lp = new long;
boost::scoped_ptr<long> sp ( lp );
BOOST_TEST( sp.get() == lp );
BOOST_TEST( lp == sp.get() );
BOOST_TEST( &*sp == lp );
*sp = 1234568901L;
BOOST_TEST( *sp == 1234568901L );
BOOST_TEST( *lp == 1234568901L );
long * lp2 = new long;
boost::scoped_ptr<long> sp2 ( lp2 );
sp.swap(sp2);
BOOST_TEST( sp.get() == lp2 );
BOOST_TEST( sp2.get() == lp );
sp.reset(NULL);
BOOST_TEST( sp.get() == NULL );
}
void main()
{
test();
}
boost::scoped_ptr和std::auto_ptr的選?。?BR>boost::scoped_ptr和std::auto_ptr的功能和操作都非常類似,如何在他們之間選取取決于是否需要轉(zhuǎn)移所管理的對象的所有權(quán)(如是否需要作為函數(shù)的返回值)。如果沒有這個需要的話,大可以使用boost::scoped_ptr,讓編譯器來進(jìn)行更嚴(yán)格的檢查,來發(fā)現(xiàn)一些不正確的賦值操作。
二. shared_ptr
boost::scoped_ptr雖然簡單易用,但它不能共享所有權(quán)的特性卻大大限制了其使用范圍,而boost::shared_ptr可以解決這一局限。顧名思義,boost::shared_ptr是可以共享所有權(quán)的智能指針,首先讓我們通過一個例子看看它的基本用法:
#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同時擁有了implementation對象的訪問權(quán)限,且當(dāng)sp1和sp2都釋放對該對象的所有權(quán)時,其所管理的的對象的內(nèi)存才被自動釋放。在共享對象的訪問權(quán)限同時,也實(shí)現(xiàn)了其內(nèi)存的自動管理。
boost::shared_ptr的內(nèi)存管理機(jī)制:
boost::shared_ptr的管理機(jī)制其實(shí)并不復(fù)雜,就是對所管理的對象進(jìn)行了引用計(jì)數(shù),當(dāng)新增一個boost::shared_ptr對該對象進(jìn)行管理時,就將該對象的引用計(jì)數(shù)加一;減少一個boost::shared_ptr對該對象進(jìn)行管理時,就將該對象的引用計(jì)數(shù)減一,如果該對象的引用計(jì)數(shù)為0的時候,說明沒有任何指針對其管理,才調(diào)用delete釋放其所占的內(nèi)存。
上面的那個例子可以的圖示如下:
1.sp1對implementation對象進(jìn)行管理,其引用計(jì)數(shù)為1
2.增加sp2對implementation對象進(jìn)行管理,其引用計(jì)數(shù)增加為2
3.sp1釋放對implementation對象進(jìn)行管理,其引用計(jì)數(shù)變?yōu)?
4.sp2釋放對implementation對象進(jìn)行管理,其引用計(jì)數(shù)變?yōu)?,該對象被自動刪除
boost::shared_ptr的特點(diǎn):
和前面介紹的boost::scoped_ptr相比,boost::shared_ptr可以共享對象的所有權(quán),因此其使用范圍基本上沒有什么限制(還是有一些需要遵循的使用規(guī)則,下文中介紹),自然也可以使用在stl的容器中。另外它還是線程安全的,這點(diǎn)在多線程程序中也非常重要。
boost::shared_ptr的使用規(guī)則:
boost::shared_ptr并不是絕對安全,下面幾條規(guī)則能使我們更加安全的使用boost::shared_ptr:
1.避免對shared_ptr所管理的對象的直接內(nèi)存管理操作,以免造成該對象的重釋放
2.shared_ptr并不能對循環(huán)引用的對象內(nèi)存自動管理(這點(diǎn)是其它各種引用計(jì)數(shù)管理內(nèi)存方式的通?。?。
3.不要構(gòu)造一個臨時的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());
}
三. weak_ptr
循環(huán)引用:
引用計(jì)數(shù)是一種便利的內(nèi)存管理機(jī)制,但它有一個很大的缺點(diǎn),那就是不能管理循環(huán)引用的對象。一個簡單的例子如下:
#include <string>
#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
class parent;
class children;
typedef boost::shared_ptr<parent> parent_ptr;
typedef boost::shared_ptr<children> children_ptr;
class parent
{
public:
~parent() { std::cout <<"destroying parent\n"; }
public:
children_ptr children;
};
class children
{
public:
~children() { std::cout <<"destroying children\n"; }
public:
parent_ptr parent;
};
void test()
{
parent_ptr father(new parent());
children_ptr son(new children);
father->children = son;
son->parent = father;
}
void main()
{
std::cout<<"begin test...\n";
test();
std::cout<<"end test.\n";
}
運(yùn)行該程序可以看到,即使退出了test函數(shù)后,由于parent和children對象互相引用,它們的引用計(jì)數(shù)都是1,不能自動釋放,并且此時這兩個對象再無法訪問到。這就引起了c++中那臭名昭著的內(nèi)存泄漏。
一般來講,解除這種循環(huán)引用有下面有三種可行的方法:
1.當(dāng)只剩下最后一個引用的時候需要手動打破循環(huán)引用釋放對象。
2.當(dāng)parent的生存期超過children的生存期的時候,children改為使用一個普通指針指向parent。
3.使用弱引用的智能指針打破這種循環(huán)引用。
雖然這三種方法都可行,但方法1和方法2都需要程序員手動控制,麻煩且容易出錯。這里主要介紹一下第三種方法和boost中的弱引用的智能指針boost::weak_ptr。
強(qiáng)引用和弱引用
一個強(qiáng)引用當(dāng)被引用的對象活著的話,這個引用也存在(就是說,當(dāng)至少有一個強(qiáng)引用,那么這個對象就不能被釋放)。boost::share_ptr就是強(qiáng)引用。
相對而言,弱引用當(dāng)引用的對象活著的時候不一定存在。僅僅是當(dāng)它存在的時候的一個引用。弱引用并不修改該對象的引用計(jì)數(shù),這意味這弱引用它并不對對象的內(nèi)存進(jìn)行管理,在功能上類似于普通指針,然而一個比較大的區(qū)別是,弱引用能檢測到所管理的對象是否已經(jīng)被釋放,從而避免訪問非法內(nèi)存。
boost::weak_ptr
boost::weak_ptr<T>是boost提供的一個弱引用的智能指針,它的聲明可以簡化如下:
namespace boost {
template<typename T> class weak_ptr {
public:
template <typename Y>
weak_ptr(const shared_ptr<Y>& r);
weak_ptr(const weak_ptr& r);
~weak_ptr();
T* get() const;
bool expired() const;
shared_ptr<T> lock() const;
};
}
可以看到,boost::weak_ptr必須從一個boost::share_ptr或另一個boost::weak_ptr轉(zhuǎn)換而來,這也說明,進(jìn)行該對象的內(nèi)存管理的是那個強(qiáng)引用的boost::share_ptr。boost::weak_ptr只是提供了對管理對象的一個訪問手段。
boost::weak_ptr除了對所管理對象的基本訪問功能(通過get()函數(shù))外,還有兩個常用的功能函數(shù):expired()用于檢測所管理的對象是否已經(jīng)釋放;lock()用于獲取所管理的對象的強(qiáng)引用指針。
通過boost::weak_ptr來打破循環(huán)引用
由于弱引用不更改引用計(jì)數(shù),類似普通指針,只要把循環(huán)引用的一方使用弱引用,即可解除循環(huán)引用。對于上面的那個例子來說,只要把children的定義改為如下方式,即可解除循環(huán)引用:
class children
{
public:
~children() { std::cout <<"destroying children\n"; }
public:
boost::weak_ptr<parent> parent;
};
最后值得一提的是,雖然通過弱引用指針可以有效的解除循環(huán)引用,但這種方式必須在程序員能預(yù)見會出現(xiàn)循環(huán)引用的情況下才能使用,也可以是說這個僅僅是一種編譯期的解決方案,如果程序在運(yùn)行過程中出現(xiàn)了循環(huán)引用,還是會造成內(nèi)存泄漏的。因此,不要認(rèn)為只要使用了智能指針便能杜絕內(nèi)存泄漏。畢竟,對于C++來說,由于沒有垃圾回收機(jī)制,內(nèi)存泄漏對每一個程序員來說都是一個非常頭痛的問題。
相關(guān)文章
C語言實(shí)現(xiàn)隨機(jī)生成6位數(shù)密碼
這篇文章主要為大家詳細(xì)介紹了如何使用C語言實(shí)現(xiàn)一個簡單而實(shí)用的隨機(jī)密碼生成器,該生成器將生成包含字母、數(shù)字和特殊字符的隨機(jī)密碼,有需要的小伙伴可以參考下2023-11-11C++11中內(nèi)聯(lián)函數(shù)(inline)用法實(shí)例
內(nèi)聯(lián)函數(shù)本質(zhì)還是一個函數(shù),但在聲明的時候,函數(shù)體要和聲明結(jié)合在一起,否則編譯器將它作為普通函數(shù)來對待,下面這篇文章主要給大家介紹了關(guān)于C++11中內(nèi)聯(lián)函數(shù)(inline)的相關(guān)資料,需要的朋友可以參考下2022-10-10C++實(shí)現(xiàn)猜數(shù)小游戲的實(shí)現(xiàn)
這篇文章主要介紹了C++實(shí)現(xiàn)猜數(shù)小游戲的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02Matlab實(shí)現(xiàn)別踩白塊小游戲的示例代碼
別踩白塊是一款音樂類休閑游戲,游戲的玩法不難,只需跟著音樂的節(jié)奏點(diǎn)中對的方塊即可。本文將用Matlab實(shí)現(xiàn)這一經(jīng)典游戲,感興趣的可以了解一下2022-03-03關(guān)于STL中vector容器的一些總結(jié)
vector作為STL提供的標(biāo)準(zhǔn)容器之一,是經(jīng)常要使用的,有很重要的地位,并且使用起來也是灰常方便。vector又被稱為向量,vector可以形象的描述為長度可以動態(tài)改變的數(shù)組,功能和數(shù)組較為相似2013-09-09