高效使用auto_ptr

auto_ptr是C++标准库中<memory>为了解决资源泄漏的问题提供的一个智能指针类模板。auto_ptr的实现原理是RAII,在构造的时获取资源,在析构的时释放资源。

下面通过一个例子掌握auto_ptr的使用和注意事项。

事例类的定义:

#pragma once
#include <iostream>
using namespace std;
class Test
{
public:
    Test();
    ~Test(void);
    int id;
    int GetId();

};
#include "Test.h"
int count=0;
Test::Test()
{
    count++;
    id=count;    
    cout<<"Create Test"<<this->id<<endl;
}


Test::~Test(void)
{
    cout<<"Destory Test"<<this->id<<endl;
}
int Test::GetId()
{

    return id;
}

auto_ptr的使用:

#include "Test.h"
#include <memory>
using namespace std;
void Sink(auto_ptr<Test> a)
{
    cout <<"Sink ";
    ///*转移所有权给a,此时test1无效了,在函数中为形参,函数结束则释放。
}
auto_ptr<Test> Source()
{
    auto_ptr<Test> a(new Test());
    return a;
}
int main(int arg,char * agrs)
{
    
    auto_ptr<Test> test1=Source();
    auto_ptr<Test> test2_1(new Test());
    auto_ptr<Test> test2_2=test2_1; /*转移所有权,此时test2_1无效了*/
    Sink(test1);

    cout <<"test2_2 Id "<< test2_2->GetId()<<endl;
    // cout << test2_1->GetId()<<endl;//出错,此时test2_1无效,
    
    return 0;
}

运行结果:

posted @ 2014-04-27 14:20  shencheng5721  阅读(769)  评论(8)    收藏  举报