Two step method to achieve deep copy -① ② copy constructor assignment operator overloading

. 1 #include <the iostream>
 2 #include < String >
 . 3  the using  namespace STD;
 . 4  class the Test {
 . 5  Private :
 . 6          int * m_pointer;
 . 7  public :
 . 8          the Test () {
 . 9                  m_pointer = NULL;
 10          }
 . 11          the Test ( int I) {
 12 is                  m_pointer = new new  int (I);
 13 is          }
 14          // deep copy to accomplish two things ① copy constructor
15          the Test ( const the Test & obj) {
 16                  m_pointer = new new  int (* obj.m_pointer);
 . 17          }
 18 is          // ② Overload operator function
 19          // return reference value is the reason: continuous assignment; and the parameters must also be const reference 
20 is          the Test & operator = ( const the Test & obj) {
 21 is                  // avoid assignment ourselves 
22 is                  IF ( the this ! = & obj) {
 23 is                          // here only for deep copy 
24                          Delete m_pointer;
 25                          m_pointer =new new  int (* obj.m_pointer);
 26 is                  }
 27          // returns the current object 
28          return * the this ;
 29          }
 30         }
 31 is          void Print () {
 32                  COUT << " m_pointer = " << m_pointer << endl;
 33 is  }
 34 is          // only when the application memory space in the heap will custom destructor
 35          // memory on the stack without custom destructor 
36          ~ the Test () {
 37 [                  Delete m_pointer;
 38 is          }
 39 };
 40  int main () {
 41 is          the Test T1 ( 25 );
 42 is          the Test T2;
 43 is          T2 = T1;
 44 is          t1.print ();
 45          t2.print ();
 46 is          return  0 ;
 47  }
 48  
49  
50  The result:
 51 is m_pointer = 0x2309c20 
52 is m_pointer = 0x2309c40

 

Guess you like

Origin www.cnblogs.com/DXGG-Bond/p/11874073.html