scoped_ptr

2387 ワード

scoped_ptrはauto_に似ていますptrのスマートポインタは、newオペレータがスタックに割り当てたダイナミックオブジェクトをパッケージし、ダイナミックに作成されたオブジェクトがいつでも正確に削除されることを保証しますが、重要なのはscoped_です.ptrはオブジェクトの管理権を取得し、そこから取り戻すことができません.
オブジェクトのプロファイル時に1回だけ解放され、オブジェクトのプロファイル時にメモリが自動的に解放されます.
source code

template<class T>
class scoped_ptr{
private:
    T *px;
    //private             
    scoped_ptr(scoped_ptr const &);
    scoped_ptr & operator=(scoped_ptr const &);
public:
    explicit scoped_ptr(T * p =0);
    ~scoped_ptr();
    //     ,      ,  p    ,scoped_ptr        
    void reset(T* p=0);
    T & operator*()const;
    T * operator->()const;
    //  scoped_ptr         ,          delete  
    T * get()const;

    operator unspecified-bool-type() const;
    void swap(scoped_ptr & b);
};


使用法:コピーと割り当ては許可されていません

#include<boost/smart_ptr.hpp>
#include<iostream>
using namespace boost;
using namespace std;

class A
{
public:
    A(){
        cout << "A()" << endl;
    }
    ~A(){
        cout << "~A()" << endl;
    }
};

int main()
{
    scoped_ptr<int> p1(new int);
    *p1 = 100;
    cout << *p1 << endl;
    scoped_ptr<int> p2(new int);
    *p2 = 200;
    cout << *p2 << endl;
    //p1 = p2;       
    p1.reset();//now p is null
    if(p1)
        cout << *p1 << endl;//this code will not be execute
    scoped_ptr<A> p3(new A);
}


100
200
A()
~A()

auto_ptrは譲渡可能です

#include<boost/smart_ptr.hpp>
#include<iostream>
#include<cassert>
using namespace boost;
using namespace std;

int main()
{
    auto_ptr<int> ap(new int(10));
    cout << *ap << endl;
    scoped_ptr<int> sp(ap);//now ap is null
    assert(ap.get()==0);
    ap.reset(new int(101));
    cout << *ap << "," << *ap.get() << endl;
}

10
101,101