smart_ptr庫
boost.smart_ptr庫提供了六種智能指針,包括scope_ptr、scoped_array、shared_ptr、shared_array、weak_ptr和intrusive_ptr。它們是輕量級的對象,速度和原始指針相差無幾,都是異常安全的。
需要包含頭文件
#include<boost/smart_ptr.hpp>
using namespace boost;
scoped_ptr
類似於auto_prt/unique_ptr的智能指針,它的所有權更加嚴格,不能轉讓,一旦scoped_ptr獲取了對象的管理權,我們就無法再從它那裏取回來。
①拷貝構造函數和賦值操作符都聲明爲私有,保證被它管理的指針不能被轉讓所有權。
②reset()重置scoped_ptr,刪除原來保存的指針,再保存新的指針值p。
③用operator *()和operator ->()重載解引用操作符和箭頭操作符,以模仿被代理的原始指針的行爲。
④提供了一個bool語境中自動轉換成bool值的功能,用來測試scoped_ptr是否持有一個有效的指針。
⑤swap()交換兩個scoped_ptr保存的原始指針。
⑥get()返回scoped_ptr內部保存的原始指針。
用法:
#include <iostream>
#include <string>
#include <boost/smart_ptr.hpp>
using namespace std;
using namespace boost;
int main()
{
//構造對象
scoped_ptr<string> sp(new string("text"));
//使用顯式bool轉型
assert(sp);
//空指針比較
assert(sp != nullptr);
//輸出
cout << *sp << endl;
cout << sp->size() << endl;
//錯誤,不能拷貝或賦值
//scoped_ptr<string> sp2 = sp;
//錯誤不能使用++或者--等操作符,只能使用 *和->
//sp++;
getchar();
return 0;
}
由於scoped_ptr類不能拷貝和賦值,所以一個類持有scoped_ptr成員變量,那麼這個類也是不可拷貝和賦值的。
對比unique_ptr
unique_ptr是C++11標準中的智能指針,它不僅能夠代理new 創建的單個對象,也能夠代理new[ ]創建的數組對象,也就是說它結合了scoped_ptr和scoped_array兩者的能力。
scoped_array
它很像 scoped_ptr,它包裝了new[ ]操作符在堆上分配的動態數組。
scoped_array的接口和功能幾乎與scoped_ptr是相同的。
①構造函數接受的指針p必須是new[ ]的結果,而不能是new表達式的結果。
②沒有*、->操作符重載,因爲scoped_array持有的不是一個普通指針。
③提供operator[ ]操作符重載,可以像普通數組一組下標訪問元素。
④沒有begin()、end()等類似容器的迭代器操作函數。
用法:
#include <iostream>
#include <string>
#include <boost/smart_ptr.hpp>
using namespace std;
using namespace boost;
int main()
{
//構造對象
scoped_array<int> sa(new int[100]);
//使用標準庫算法賦值數據
fill_n(&sa[0], 100, 5);
//用起來就像普通數組
sa[10] = sa[20] + sa[30];
//錯誤用法,不能通過編譯
//*(sa + 1) = 20;
getchar();
return 0;
}
對比unique_ptr
unique_ptr用法與scoped_array基本相同,但模板參數中需要聲明爲數組類型。
unique_ptr<int []> up(new int[10])
使用建議
scoped_array的功能有限,不能動態增長,沒有邊界檢查,也沒有迭代器支持,不能搭配STL算法。
在需要動態數組的情況下我們應該使用std::vector,不推薦使用scoped_array。