luqingfei@C++

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

智能指针auto_ptr运用实例:常数型智能指针的特性

//展示const 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()
{
    
const auto_ptr<int> p(new int(42));
    
const auto_ptr<int> q(new int (0));
    
const auto_ptr<int> r;

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

    
*= *p;
    
//*r = *p;    // ERROR: undefined behavior 对于一个“未指向任何对象”的auto_ptr进行提领(dereference)操作,C++标准规格,
    
//这会导致未定义行为,比较如说导致程序的崩溃。
    *= -77;

    cout 
<< "after assigning values:" << endl;
    cout 
<< " p: " << p << endl;
    cout 
<< " q: " << q << endl;
    cout 
<< " r: " << r << endl;

    
//q = p; // ERROR at compile time
    
//r = p; // ERROR at compile time
}

输出结果:
after initialization:
 p: 42
 q: 0
 r: NULL
after assigning values:
 p: -77
 q: 42
 r: NULL
请按任意键继续. . .

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


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


导航

<2011年1月>
2627282930311
2345678
9101112131415
16171819202122
23242526272829
303112345

统计

留言簿(6)

随笔分类(109)

随笔档案(105)

Blogers

Game

Life

NodeJs

Python

Useful Webs

大牛

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜