导航:[首页]->[cpp]->[一个通用的智能指针]
    // 通用智能指针
    template<typename T,typename RET,RET(*FINI)(T*)>
    class AutoPtr{
    public:
        AutoPtr():m_ptr_(NULL){};
        ~AutoPtr(){
            this->Release();
        }

        void    Release(){
            if(this->m_ptr_){
                FINI(m_ptr_);
                this->m_ptr_ = NULL;
            }
        }

        T*      Dettach(){
            T* ptr_ = this->m_ptr_;
            this->m_ptr_ = NULL;
            return ptr_;
        }

        void    Attach(T* ptr)
        {
            if(ptr == this->m_ptr_)
                return;
            this->Release();
            this->m_ptr_ = ptr;
        }
    private:
        T*      m_ptr_;
    };

    // c语言的智能指针
    inline void     CFree(char* ptr){
        if(ptr){
            ::free(ptr);
        }
    }
    typedef AutoPtr<char,void,CFree> CAutoPtr;

    // cpp智能指针(delete)
    template <typename T>
    inline void     CplusFree(T* ptr){
        if(ptr){
            delete ptr;
        }
    }
    template<typename T>
    class CplusAutoPtr : public AutoPtr<T,void,CplusFree>{
    };
    // cpp智能指针(delete [])
    template <typename T>
    inline void     CplusFreeEx(T* ptr){
        if(ptr){
            delete [] ptr;
        }
    }
    template<typename T>
    class CplusExAutoPtr : public AutoPtr<T,void,CplusFreeEx>{
    };




    使用

    int main(int argc, char **argv)
    {
        AutoPtr<FILE,int,fclose> xxx;
        FILE* fp_ = fopen("c:/xx","w+");
        xxx.Attach(fp_);

        CAutoPtr cptr_;
        char* ptr_ = (char*)::malloc(100);
        cptr_.Attach(ptr_);

        char* ptr1_ = new char[100];
        CplusExAutoPtr<char> cplus_ptr_;
        cplus_ptr_.Attach(ptr1_);


        printf("hello world\n");
        return 0;
    }