dobest
C++博客
::
首页
::
联系
::
聚合
::
管理
1 Posts :: 2 Stories :: 0 Comments :: 0 Trackbacks
常用链接
我的随笔
我的评论
我参与的随笔
留言簿
(3)
给我留言
查看公开留言
查看私人留言
我参与的团队
随笔档案
2008年3月 (1)
文章档案
2008年6月 (1)
2008年4月 (1)
搜索
最新评论
c++智能指针auto_ptr用法实例一(p47页)
1
#include
<
iostream
>
2
#include
<
memory
>
3
4
using
namespace
std;
5
/**/
/*
define output operator for auto_ptr
6
* - print object value or NULL
7
*/
8
9
template
<
class
T
>
10
ostream
&
operator
<<
(ostream
&
strm,
const
auto_ptr
<
T
>&
p)
11
{
12
//
does p own an object ?
13
14
if
(p.
get
()
==
NULL)
15
{
16
strm
<<
"
NULL
"
;
//
NO: print NULL
17
}
18
else
19
{
20
strm
<<
*
p;
//
YES: print the object
21
}
22
return
strm;
23
}
24
25
int
main()
26
{
27
auto_ptr
<
int
>
p(
new
int
(
42
));
28
auto_ptr
<
int
>
q;
29
30
cout
<<
"
after initialization:
"
<<
endl;
31
cout
<<
"
p:
"
<<
p
<<
endl;
32
cout
<<
"
q:
"
<<
q
<<
endl;
33
34
q
=
p;
35
cout
<<
"
after assigning auto pointers:
"
<<
endl;
36
cout
<<
"
p:
"
<<
p
<<
endl;
37
cout
<<
"
q:
"
<<
q
<<
endl;
38
39
*
q
+=
13
;
40
p
=
q;
41
cout
<<
"
after change and reassingnment:
"
<<
endl;
42
cout
<<
"
p:
"
<<
p
<<
endl;
43
cout
<<
"
q:
"
<<
q
<<
endl;
44
45
system(
"
pause
"
);
46
47
}
48
49
智能指针不同于一般的指针,赋值后,一个智能指针把值赋给另一个智能指针后,拥有权转移到被赋值的智能指针.详见《c++ 标准程序库》p47页.
posted on 2008-06-17 17:21
叶家明
阅读(401)
评论(0)
编辑
收藏
引用
Copyright @ 叶家明
Powered by:
.Text
and
ASP.NET
Theme by:
.NET Monster