If the programmer does not define a copy constructor, the compiler automatically generates a default copy constructor. What problems may arise? The following is an example 1. No copy constructor # Include <iostream> Class myclass { Public: Myclass (int) { B = new int (); } Int * myget () { Return B; } Protected: PRIVATE: Int * B; }; Int main () { Myclass class1 (5 ); Myclass class2 (class1 ); STD: cout <"class1. B =" <class1.myget () <"<" * B = "<* (class1.myget () <STD :: endl; STD: cout <"class1. B =" <class2.myget () <"<" * B = "<* (class2.myget () <STD :: endl; } Execution result: That is, the data members of two objects Save the same memory address. 2. copy constructor (deep copy) # Include <iostream> Class myclass { Public: Myclass (int) { B = new int (); } Myclass (const myclass & class2) { B = new int (* (class2. B )); } Int * myget () { Return B; } Protected: PRIVATE: Int * B; }; Int main () { Myclass class1 (5 ); Myclass class2 (class1 ); STD: cout <"class1. B =" <class1.myget () <"<" * B = "<* (class1.myget () <STD :: endl; STD: cout <"class1. B =" <class2.myget () <"<" * B = "<* (class2.myget () <STD :: endl; } Execution result: That is, the data members of two objects are different, but the saved values are 5. A: The default copy constructor is a shortest constructor. When an object contains pointer data members and uses it to initialize another object of the same type, the default copy constructor can only copy the value of the data member of the object to another object, rather than copying the entire object. In this way, the same memory unit may be released twice, causing program running errors. |