智能指針簡單實現-auto_ptr

AutoPtr定義

//AutoPtr
template<typename T>
class AutoPtr{
public:
    AutoPtr(){
        m_ptr = NULL; 
        cout<<"create: m_ptr()."<<endl;
    }
    
    AutoPtr(AutoPtr<T>& p){
        m_ptr = p.m_ptr;
        p.m_ptr = NULL; 
        cout<<"create: m_ptr(&p)."<<endl;
    }
    
    AutoPtr(T* p):m_ptr(p){
        cout<<"create: m_ptr(*p)."<<endl;
    }
    
    AutoPtr& operator=(AutoPtr<T>& p){
        if(this != &p){
            cout<<"operator =: this != p "<<endl;
            delete m_ptr;
            m_ptr = p.m_ptr;
            p.m_ptr = NULL;
        }else{
            cout<<"operator =: this == p "<<endl;
        }
        
        return *this;
    }
    
    ~AutoPtr(){
        if (NULL != m_ptr ){
            cout<<"delete: m_ptr is not null."<<endl;
            delete m_ptr;
        }else{
            cout<<"delete: m_ptr is null."<<endl;
        }
    }
    
    T& operator*(){
        return *m_ptr;
    }
    
    T* operator->(){
        return m_ptr;
    }
    
protected:
    T* m_ptr;
};

測試代碼

//Test
int main()
{
    cout<<"Test start."<<endl;
    AutoPtr<int> p1(new int(100));
    cout<<"p1 = "<<*p1<<endl;
    
    *p1 = 110;
    cout<<"p1 = "<<*p1<<endl;
    
    AutoPtr<int> p2(new int(200));
    cout<<"p2 = "<<*p2<<endl;
    
    AutoPtr<int> p3;
    p3 = p1;
    AutoPtr<int> p4 = p2;
    cout<<"p3 = "<<*p3<<", p4 = "<<*p4<<endl;
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章