luqingfei@C++

为中华之崛起而崛起!
兼听则明,偏听则暗。

智能指针auto_ptr运用实例:移转拥有权的行为

#include <iostream>
#include 
<memory>
using namespace std;

/* define output operator for auto_ptr
*  print object value or NULL
*/

template
<class T>
ostream
& operator<< (ostream& strm, const auto_ptr<T>& p)
{
    
// does p own an object ?
    if (p.get() == NULL)
    {
        strm 
<< "NULL"// NO:print NULL
    }
    
else
    {
        strm 
<< *p;     // YES:print the object
    }

    
return strm;
}

int main()
{
    auto_ptr
<int> p(new int(42));
    auto_ptr
<int> q;

    cout 
<< "after initialization:" << endl;
    cout 
<< " p: " << p << endl;
    cout 
<< " q: " << q << endl;

    q 
= p;
    cout 
<< "after assigning auto pointers:" << endl;
    cout 
<< " p: " << p << endl;
    cout 
<< " q: " << q << endl;

    
*+= 13// change value of the object q owns
    p = q;
    cout 
<<  "after change and reassingnment:" << endl;
    cout 
<< " p: " << p << endl;
    cout 
<< " q: " << q << endl;
}


输出结果:
after initialization:
 p: 42
 q: NULL
after assigning auto pointers:
 p: NULL
 q: 42
after change and reassingnment:
 p: 55
 q: NULL
请按任意键继续. . .




 

posted on 2011-01-04 14:29 luqingfei 阅读(359) 评论(0)  编辑 收藏 引用 所属分类: C++基础


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


导航

<2024年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

统计

留言簿(6)

随笔分类(109)

随笔档案(105)

Blogers

Game

Life

NodeJs

Python

Useful Webs

大牛

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜