Tag:c++ smart pointer class smart pointer
Smart pointer class//----------------------------------------//1. Cardinality is placed in the usage count class//actual class point-and usage count class-base data//Usage Count class u_ptr{ Friend class hasptr;//friend class int *ip;//This is the base to protect, according to size_t use; u_ptr (int *p): IP (P), use (1) {}~u_ptr () {delete ip;}}; Class hasptr//the actual class {public:hasptr (int *p,int i):p tr (New U_ptr ((p)), Val (i) {}hasptr (const hasptr &orig):p TR (orig.ptr ), Val (orig.val) {++ptr->use;} hasptr& operator= (const hasptr &RHS) {++rhs.ptr->use;if (--ptr->use = = 0) Delete ptr;ptr=rhs.ptr;val= Rhs.val;return *this;} ~hasptr () {if (--ptr->use = = 0) delete ptr;} Private:u_ptr *ptr;int val;};/ /----------------------------------------------//2. The base is placed in the actual class//the actual class points to the use of the Count class, the actual class also points to the same base data//Usage Count class U_ptr{friend Class hasptr;//friend class size_t use; U_ptr (): Use (1) {}~u_ptr () {}};class hasptr//actual class {public:hasptr (int *p,int i):p tr (new u_ptr), IP (p) val (i) {}hasptr (const Hasptr &orig):p tr (orig.ptr), IP (ORIG.P); Val (orig.val) {++ptr->use;} hasptr& operator= (const hasptr &RHS) {++rhs.ptr->use;if (--ptr->use = = 0) {Delete Ptr;deleTe IP;} Ptr=rhs.ptr;ip=rhs.ip;val=rhs.val;return *this;} ~hasptr () {if (--ptr->use = = 0) {delete ptr;delete IP;}} Private:int *ip;//This is to protect the base according to U_ptr *ptr;int val;};/ /When defining a value class//Copying an object, copy the base data pointed to by the pointer at the same time
Smart Pointer class