auto_ptr作为函数参数

 1#include "stdafx.h"
 2
 3#include <iostream>
 4
 5#include <memory>
 6
 7using namespace std;
 8
 9 
10
11template <class T>
12
13ostream& operator<< (ostream& os, const auto_ptr<T> &p)
14
15{
16
17       if(p.get() == NULL)
18
19              os<<"NULL";
20
21       else
22
23              os<< *p;
24
25       return os;
26
27}
如果不用引用,在函数传参的时候会将指针的控制权交给函数的参数,之后程序就会出问题。
如果不用const,还没想出会有什么后果。

使用auto_ptr需注意的地方:
1 它不能用作数组或容器的对象。
2
它不能进行一般意义的赋值和复制。
3
它的指针算数没有意义。
你最好不要用它来传递参数,当不得不用的时候必须用const引用才行。
5 同时不能有两个以上的auto_ptr指向同一个值。
参考:
http://blog.csdn.net/vagrxie/archive/2007/10/12/1821091.aspx
posted on 2009-08-28 09:56  lbsx  阅读(612)  评论(0编辑  收藏  举报