码迷,mamicode.com
首页 > 其他好文 > 详细

auto_ptr 用例1

时间:2015-03-10 19:04:56      阅读:122      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!