首页 > 其他 > 详细

auto_ptr 用例1

时间:2015-03-10 19:02:54      阅读:219      评论:0      收藏:0      [点我收藏+]

auto_ptr // 头文件 <memory>

 

std::auto_ptr<ClassA> ptr1(new ClassA); // ok
std::auto_ptr<ClassA> ptr2 = new ClassA; // error 不允许 赋值(assign)初始化方式
auto_ptr赋值会导致所有权的转移

 

auto_ptr错误运用:
1.auto_ptr之间不能共享拥有的所有权
2.不能让auto_ptr指向数组,因为是透过delete而没有delete[

 

1.所有权的变更

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

template <class T>
ostream& operator<<(ostream& out, const auto_ptr<T>& p)
{
    if(p.get() == NULL)
        out<<"NULL";
    else
        out<<*p;
        
    return out;    
}

int main()
{
    auto_ptr<int> p(new int(42));
    auto_ptr<int> q;
    
    cout<<"after init..\n";
    cout<<"p = "<<p<<endl;
    cout<<"q = "<<q<<endl;
    
    q = p;
    cout<<"after assign..\n";
    cout<<"p = "<<p<<endl;
    cout<<"q = "<<q<<endl;    
    
    *q += 13;
    p = q;
    cout<<"after change and assign..\n";
    cout<<"p = "<<p<<endl;
    cout<<"q = "<<q<<endl;        
    
}

输出结果:

after init..
p = 42
q = NULL
after assign..
p = NULL
q = 42
after change and assign..
p = 55
q = NULL

auto_ptr 用例1

原文:http://www.cnblogs.com/sylar-liang/p/4326623.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!