Smart pointer (smart pointer) is a class that stores pointers to dynamically allocated (heap) objects and is able to automatically delete objects that point to them at the appropriate time, ensuring that dynamically allocated objects are destroyed correctly.
The smart pointer for the standard library is auto_ptr. The smart pointer family of the boost library is functionally expanded.
1.auto_ptr
Auto_ptr precautions are as follows.
①AUTO_PTR cannot share ownership.
②auto_ptr cannot point to an array.
③auto_ptr cannot be a container member.
④ cannot initialize auto_ptr with assignment manipulation.
2.boost_ptr
The boost library extends the smart pointer family and makes it easy to use.
①scoped_ptr-<boost/scoped_ptr.hpp>: Simple single object unique ownership, not replicable.
②scoped_array<boost/scoped_array.hpp>: Simple array unique ownership, cannot be copied.
③shared_ptr<boost/shared_ptr.hpp>: Ownership of objects shared in multiple pointers.
④SHARED_ARRAY<BOOST/SHARED_ARRAY.HPP>: Array ownership shared across multiple pointers.
⑤WEAK_PTR<BOOST/WEAK_PTR.HPP>: An observer belonging to the Shared_ptr object without ownership.
⑥intrusive_ptr<boost/intrusive_ptr.hpp>: An object with an intrusive reference count shares ownership.
3.smart_ptr
Simulates the implementation of shared object ownership pointers, simulating shared_ptr. The sample code is as follows.
Template <typename t>class smartptr{public: smartptr (t* p=0):p TR (P), Puse (New size_t ()) {} Smartptr ( Const smartptr& SRC):p tr (src.ptr), Puse (src.puse) {++*puse;} smartptr& operator= (const smartptr& RHS) { ++*rhs.puse; Decruse (); ptr = rhs.ptr; Puse = Rhs.puse; return *this; } t* operator-> () {if (PTR) return ptr; else return null;} t& operator* () {if (PTR) return *ptr; else return null;} ~smartptr () {decruse ();} size_t Usecount () {return *puse;} Private: void Decruse () { if (--*puse = = 0) { delete ptr; ptr = null; Delete puse; Puse = null; } } t* ptr; size_t* Puse;};
C + + Technical issues Summary-9th smart pointer