boost中智能指針主要包括scoped_ptr,scoped_array,shared_ptr,shared_array;
1.scoped_ptr
scoped_ptr:跟auto_ptr很像,但是它有更嚴格的管理權也更安全。當離開作用域能夠自動釋放的指針。因爲它是不傳遞所有權的。事實上它
明確禁止任何想要這樣做的企圖!這在你需要確保指針任何時候只有一個擁有者時的任何一種情境下都是非常重要的。
頭文件:#include <boost/scoped_ptr.hpp>using namespace boost;
函數接口定義:
namespace boost {
template<class T> class scoped_ptr : noncopyable {
public:
typedef T element_type;
explicit scoped_ptr(T * p = 0); // never throws
~scoped_ptr(); // never throws
void reset(T * p = 0); // never throws
T & operator*() const; // never throws
T * operator->() const; // never throws
T * get() const; // never throws
operator unspecified-bool-type() const; // never throws
void swap(scoped_ptr & b); // never throws
};
template<class T> void swap(scoped_ptr<T> & a, scoped_ptr<T> & b); // never throws
}
用法介紹:
#include <iostream>
#include <boost/intrusive_ptr.hpp>
using namespace boost;
using std::cout;
using std::endl;
int main()
{
scoped_ptr<string> sp(new string("test"));
cout<<*sp<<endl;//獲取string的值。 test
cout<<sp->size()<<endl;//不需要使用delete操作。不允許拷貝構造和自增操作。
sp.reset();//將sp置爲0;當爲0時自動刪除。調用string的析構函數。
int *a = sp.get();//可以得到原始指針。不推薦這麼做。
}
意義:代碼清晰,錯誤更少,沒有多餘的操作,同時效率很高,能夠跟原始指針同樣的速度。
2.shared_ptr
shared_ptr實現了引用計數型的智能指針,可以被自由拷貝和賦值,任意地方共享他,只有當計數爲0時,才能刪除它。
它更像一個智能指針,同時也是smart_ptr庫中左右價值的、最重要,用的最多的一個組件。
boost::shared_ptr的管理機制其實並不複雜,就是對所管理的對象進行了引用計數,當新增一個boost::shared_ptr對該對象進行管理時
,就將該對象的引用計數加一;減少一個boost::shared_ptr對該對象進行管理時,就將該對象的引用計數減一,
如果該對象的引用計數爲0的時候,說明沒有任何指針對其管理,才調用delete釋放其所佔的內存。
位置:#include <boost/shared_ptr.hpp>using namespace boost;
ps:這些智能指針都包含在:#include <boost/smart_ptr.hpp> 頭文件中。
類的部分常用接口定義:
完整文檔在這:http://www.boost.org/doc/libs/1_55_0/libs/smart_ptr/shared_ptr.htm
template<class T> class shared_ptr {
public:
shared_ptr(); // never throws
shared_ptr(std::nullptr_t); // never throws
~shared_ptr(); // never throws
void reset();
T & operator*() const; // never throws; only valid when T is not an array type
T * operator->() const; // never throws; only valid when T is not an array type
T * get() const;//獲取原始指針。
bool unique() const;//返回是否是唯一擁有者。
long use_count() const;//返回當前引用計數。
}
用法示例:
#include <iostream>
#include <boost/smart_ptr.hpp>
using namespace boost;
using std::cout;
using std::endl;
using std::string;
class demo
{
public:
~demo() { std::cout <<"destroying demo\n"; }
void do_something() { std::cout << "did something\n"; }
};
int main()
{
boost::shared_ptr<demo> sp1(new demo());//新建shared指針管理demo對象。
std::cout<<"Now has "<<sp1.use_count()<<" references\n";
boost::shared_ptr<demo> sp2 = sp1;
std::cout<<"Now has "<<sp2.use_count()<<" references\n";
sp1.reset();//sp1解除shared對sp1的指針管理。
std::cout<<"After Reset has "<<sp2.use_count()<<" references\n";
sp2.reset();
std::cout<<"After Reset sp2.\n";
}
/*輸出:
Now has 1 references
Now has 2 references
After Reset has 1 references
destroying demo
After Reset sp2.
*/