Smart pointers are designed to facilitate the management of dynamic memory and to automatically manage the objects pointed to by the release.
There are three kinds of smart pointers: 1, shared_ptr allows multiple pointers to the same object, 2, unique_ptr the object that the exclusive points to, and 3, weak_ptr is a companion class, which is a weak reference to the object that shared_ptr manages. These three types are defined in the memory header file.
Here is a code for implementing the smart pointers that you see on the Web:
Class U_ptr {friend class hasptr;int *ip;size_t use; u_ptr (int *p): IP (P), use (1) {cout << "U_ptr constructor called!" << Endl;} ~u_ptr () {delete Ip;cout << "u_ptr distructor called!" << Endl;}}; Class Hasptr {public:hasptr (int *p, int i):p tr (new U_ptr (P)), Val (i) {cout << "Hasptr constructor called!" <&L T "Use =" << ptr->use << Endl;} Hasptr (const hasptr& orig):p tr (orig.ptr), Val (orig.val) {++ptr->use;cout << "Hasptr copy constructor Called! "<<" use = "<< ptr->use<< Endl;} hasptr& operator= (const hasptr&); ~hasptr () {cout << "hasptr distructor called!" << "use =" << Ptr->use << endl;if (--ptr->use = = 0) delete ptr;} int *get_ptr () const {return ptr->ip;} int Get_int () const {return val;} void set_ptr (int *p) const {PTR->IP = P;} void Set_int (int i) {val = i;} int Get_ptr_val () const {return *ptr->ip;} void Set_ptr_val (int i) {*ptr->ip = i;} Private:u_ptr *ptr;int Val;}; hasptr& Hasptr::operator = (const hasptr &RHS) {//note, here the assignment operator adds 1 to the use of RHS before reducing the use count of the operands, thus preventing self-assignment ++rhs.ptr-> Use;if (--ptr->use = = 0) Delete ptr;ptr = Rhs.ptr;val = Rhs.val;return *this;}
C + + Learning notes-smart pointers