scope_ptr

来源:互联网 发布:gephi 布局算法 编辑:程序博客网 时间:2024/06/06 04:08
#include <iostream>#include <cassert>using namespace std;template <typename T>class scoped_ptr{public:    typedef T elememnt_type;    explicit scoped_ptr(T* p = 0) :px(p){ cout << "scoped_ptr construct" << endl; };    ~scoped_ptr(){ cout << "scoped_ptr deconstruct" << endl; delete px; }    T& operator*()const    {        assert(px != 0);        return *px;    }    T* operator->()const    {        assert(px != 0);        return px;    }    T* get()const    {        return px;    }    void swap(scoped_ptr& p)    {        T* temp = p.px;        p.px = px;        px = temp;    }    void reset(T* p = 0){        assert(p == 0 || p != px);        scoped_ptr<T>(p).swap(*this);//这句话很吊        //用临时对象交换指针,把p给了this对象,临时对象消亡delete this;    }    operator bool()    {        cout << "scoped_ptr operator bool()" << endl;        return px != 0;    }    bool operator!()    {        cout << "scoped_ptr bool operator!()" << endl;        return px == 0;    }private:    T* px;    scoped_ptr(const scoped_ptr& ptr);    scoped_ptr& operator=(const scoped_ptr& ptr);    bool operator==(const scoped_ptr& ptr);    bool operator!=(const scoped_ptr& ptr);};int main(){    scoped_ptr<int> p(new int(10));//scoped_ptr construct    if (p)    {        cout << "p true" << endl;//p true    }    else    {        cout << "p false"<<endl;    }    scoped_ptr<int> p2(new int(20));    p2.swap(p);    cout << *p << ends << *p2 << endl;//20 10    p2.reset(new int(100));//scoped_ptr construct scoped_ptr deconstruct     cout << *p << ends << *p2 << endl;//20 100    return 0;}

这里写图片描述