高效使用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;
}

運行結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM