代理模式 Proxy

使用一个类来代理另一个类,如智能指针auto_ptr,对智能指针的操作,实际上是对代理的指针的操作

#include <IOSTREAM>
using namespace std;

template<class T>
class auto_ptr{
public:
    explicit auto_ptr(T * p = 0){
        preal = p;
    }    
    auto_ptr(auto_ptr<T> & pother)
        :preal(pother.release()){
        
    }
    T * release(){                      //释放智能指针对其指针的拥有权,使preal = 0
        T * pold = preal;
        preal = 0;
        return pold;
    }
    
    void reset(T * p = 0){
        if(preal != p){    
            delete preal;
            preal = p;
        }
    }
    
    ~auto_ptr(){
        delete preal;
    }
    
    T * get(){
        return preal;
    }
    
    auto_ptr<T> & operator=(auto_ptr<T> & pother ){
        if( &pother != this){ //pother != *this,没有重载!=符号,会出错
            reset(pother.release());
        }
        return *this;
    }
private:
    T * preal;
};
int main(int argc, char* argv[])
{
    auto_ptr<int> a(new int(5));
    cout<<*a.get()<<endl;
    auto_ptr<int> b(a);
//    cout<<*a.get()<<endl;  出错,已经转移所有权至b
    cout<<*b.get()<<endl;
    a = a;
    b = b;
//    cout<<*a.get()<<endl;
    return 0;
}

 

posted @ 2015-07-09 22:39  朽木可雕否  阅读(129)  评论(0编辑  收藏  举报