代码改变世界

auto_ptr 用例1

2015-03-10 17:45  sylar_liang  阅读(148)  评论(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