Posted on 2011-11-07 23:00
Sivan 閱讀(1356)
評論(0) 編輯 收藏 引用 所屬分類:
Boost
scoped_ptr
1.scoped_ptr所管理的指針,所有權不能被轉讓。scoped_ptr的拷貝構造函數和賦值操作符都聲明為了私有,這樣scoped_ptr不能進行復制操作,其所含指針就不能改變所有權。
2.提供了*和->操作符的重載,這樣操作scoped_ptr對象可以像操作原始指針一樣方便,但不能進行比較、自增、自減等操作。
3.因為scoped_ptr不支持拷貝和賦值操作,所以scoped_ptr不能作為STL容器的元素。
1 #include "stdafx.h"
2 #include <string>
3 #include <vector>
4 #include <iostream>
5 #include <boost/smart_ptr.hpp>
6 using namespace boost;
7 using namespace std;
8
9 int _tmain(int argc, _TCHAR* argv[])
10 {
11 // 1.用法,在構造的時候,接受new表達式結果
12 scoped_ptr<string> sp(new string("Test scope ptr"));
13
14 // 2.模擬指針的操作
15 cout<<sp->size()<<endl;
16 cout<<*sp<<endl;
17
18 // 3.不能進行比較、自增、自減,轉移指針等操作
19 // ++sp; // 錯誤
20 // scoped_ptr<string> sp1 = sp; 構造函數為私有函數
21
22 // 4.不能作為stl容器的元素
23 // vector<scoped_ptr<string> > vecSP; // 可以通過
24 // vecSP.pop_back(sp); // 錯誤,因為scoped_ptr不支持拷貝和賦值
25
26 // 5.不能轉移所管理的指針的所有權
27 auto_ptr<string> ap(new string("Test auto ptr"));
28 scoped_ptr<string> sp2(ap);
29 assert(ap.get()==0);
30 ap.reset(new string("new test"));
31 cout<<*sp2<<endl<<*ap<<endl;
32
33 return 0;
34 }