Sivan's blog

用代码说话……
posts - 14, comments - 2, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

scoped_ptr

Posted on 2011-11-07 23:00 Sivan 阅读(1321) 评论(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 }




 

 


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理