scoed

    xiaoxiao2021-03-25  189

    防拷贝是用来进行资源管理的第二种方法,第一种是auto_ptr,资源转移auto_ptr,所谓的防拷贝就是不用拷贝构造函数和赋值运算符重载函数;但在类中又不能不写,因为系统会自动合成

    template<class T> calss scoped_ptr { public: scopedptr(T* ptr) :_ptr(ptr) {} ~scopedptr() { if(_ptr!=NULL) { delete _ptr; _ptr = NULL; } } //方法一:将拷贝构造函数和赋值运算符重载函数给成私有成员函数,给出函数定义,函数体可以为NULL,因为没有任何意义 private: //给出定义 scopedptr(const scopedptr<int>& sp) {} scopedptr<T> operator=(const scopedptr<T>& ap)//缺点:不清楚如何给出实体 {} //方法二:将拷贝构造函数和赋值运算符重载函数给成公共的类成员函数,但不给出定义 scopedptr(const scopedptr<int>& sp); scopedptr<T> operator=(const scopedptr<T>& ap);//缺点:这种情况可能会有用户在类的外面自己定义 //方法三:将拷贝构造函数和赋值运算符重载函数给成私有的成员函数,但只声明不定义 private: scopedptr(const scopedptr<int>& sp); scopedptr<T> operator=(const scopedptr<T>& ap);//防拷贝的最好的选择 //方法四:不给出拷贝构造函数和赋值运算符重载函数 //缺点:编译器会自动合成 private: T* _ptr; }; void funtest() { scopedptr<int> sp1(int new); scopedptr<int> sp2(int new); } int mian() { return 0; }
    转载请注明原文地址: https://ju.6miu.com/read-22868.html

    最新回复(0)