dobest

  C++博客 :: 首页 :: 联系 :: 聚合  :: 管理
  1 Posts :: 2 Stories :: 0 Comments :: 0 Trackbacks

常用链接

留言簿(3)

我参与的团队

搜索

  •  

最新评论

 1#include <iostream>
 2#include <memory>
 3
 4using namespace std;
 5/* define output operator for auto_ptr
 6* - print object value or NULL
 7*/

 8
 9template <class T>
10ostream& 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
25int 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    *+= 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)  编辑 收藏 引用