Skip to content

Instantly share code, notes, and snippets.

@superlayone
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save superlayone/c948e96ab3712cd412a1 to your computer and use it in GitHub Desktop.
Save superlayone/c948e96ab3712cd412a1 to your computer and use it in GitHub Desktop.
auto_ptr

###auto_ptr的实现

    
    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    template<class T>
    class auto_pointer{
    public:
    	explicit auto_pointer(T *p = 0);
    
    	template<class U>
    	auto_pointer(auto_pointer<U>& rhs);
    
    	~auto_pointer();
    
    	template<class U>
    	auto_pointer<T>& operator=(auto_pointer<U>& rhs);
    
    	T& operator*() const;
    	T* operator->() const;
    
    	T* get() const;
    	T* release();
    
    	void reset(T *p = 0);
    private:
    	T *pointee;
    
    	//template<class U>
    	//friend class auto_pointer<U>;
    };
    
    template<class T>
    inline auto_pointer<T>::auto_pointer(T *p):pointee(p){}
    
    template<class T>
    template<class U>
    inline auto_pointer<T>::auto_pointer(auto_pointer<U>& rhs):pointee(rhs.release()){}
    
    template<class T>
    inline auto_pointer<T>::~auto_pointer(){
    	delete pointee;
    	cout<<"pointee deleted...\n";
    }
    
    template<class T>
    template<class U>
    inline auto_pointer<T>& auto_pointer<T>::operator=(auto_pointer<U>& rhs){
    	if(this != &rhs){
    		reset(rhs.release());
    	}
    	return *this;
    }
    
    template<class T>
    inline T& auto_pointer<T>::operator*() const{
    	return *pointee;
    }
    
    template<class T>
    inline T* auto_pointer<T>::operator->() const{
    	return pointee;
    }
    
    template<class T>
    inline T* auto_pointer<T>::get() const{
    	return pointee;
    }
    
    template<class T>
    inline T* auto_pointer<T>::release(){
    	T *t = pointee;
    	pointee = 0;
    	return t;
    }
    
    template<class T>
    inline void auto_pointer<T>::reset(T *p){
    	if(pointee != p){
    		delete pointee;
    		pointee = p;
    	}
    }
    class A{
    
    };
    void Test(){
    	A *a = new A;
    	auto_pointer<A> b(a);
    }
    int main()
    {
    	Test();
    	system("pause");
    	return 0;
    }
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment