Three common ways to do smart pointers:
First, the original writing, the original wording can be understood as the method of pointer transfer.
Template<typename t>class autoptr{public: autoptr () :_ptr (NULL) {} autoptr (T* ptr ) :_ptr (PTR) {} ~ Autoptr () { if (_ptr) { Delete _ptr; _ptr = null ; } } autoptr< T> (AUTOPTR<T>&&NBSP;AP) : _ptr (ap._ptr) { ap._ptr = NULL; } autoptr<t>& operator = (AUTOPTR<T>&&NBSP;AP) { if (THIS&NBSP;!=&NBSP;&AP) { Delete _ptr; _ptr = ap._ ptr; ap._ptr = null; } return *this; } t& operator* () { return *_ptr; } t* gerptr () { return _ptr; }private: t* _ptr;};
Second, the evolution of the later scoped, but also known as the Guard writing. The advantage of this notation in relation to the original writing is that it is not allowed to use the overloading of copy constructs and operators, thus avoiding the problem of pointer-to-depth copies. The procedure is to declare the copy construction, the overloading of the operators, and not define them, and protect them with protected. Scoped notation is a reference to the boost library. Interested can go to understand this thing, behind still have a lot of story, in here I don't say much.
Template<class t>class scopedptr{public: scopedptr () :_ptr (NULL) {} scopedptr (T* PTR) :_ptr (PTR) {} ~scopedptr () { if (_PTR) { delete _ptr; _ptr = NULL; } } t& operator* () { return *_ptr; } T* operator-> () { return _ptr; } t* getptr () { return _ptr; }protected: //plus protected prevents users from defining overloaded functions for copy constructs and operators outside of the class scopedptr <T> (CONST&NBSP;SCOPEDPTR<T>&&NBSP;SP); // Do not allow the user to use the copy, can prevent the copy, therefore only declares does not define scopedptr<t>& operator= (const scopedptr <T>&&NBSP;SP);p rivate: t* _ptr;};
Three, the sharedptr wording
This method takes into account the problem of deep-and-dark copy and refers to the reference counter to solve the problem of shallow copy, which realizes the function that the smart pointer wants to realize.
Template<class t>class shareptr{public: shareptr (T* ptr) :_ptr (PTR) , _ Pcount (New int (1)) {} //shareptr (Shar) // :_ptr (sp._ptr) //{ // *_pcount = 1; //} ~shareptr () { if (_ptr) { if (--(* _pcount) == 0) { delete _ptr; delete _pcount; _ptr = NULL; _pCount = NULL; } _ptr = NULL; } } SharePtr<T> (CONST&NBSP;SHAREPTR<T>&&NBSP;SP) { _ptr = sp._ptr; _pcount = sp._pcount; + + (*_pcount); } shareptr<t>& operator= (const Shareptr<t>&&nBSP;SP) { if (this != &SP) { if (--(*_pcount) == 0) //here to know who to subtract one, the logic needs to be analyzed clearly { delete _ptr; delete _pCount; _ptr = NULL; _pCount = NULL; } &nBsp;_ptr = sp._ptr; _pcount = sp._pcount; ++ (*_pCount); } return * This; }private: t* _ptr; int* _ Pcount;};
This article is from "drip" blog, please be sure to keep this source http://10740329.blog.51cto.com/10730329/1766046
The original writing, scoped and shared notation of "C + +" smart pointers