. 1 #include <the iostream> 2 #include < String > . 3 the using namespace STD; . 4 // constructor (copy constructor), destructor, 5 / * deep copy: refers to the class provides the compiler given a default copy constructor when the copy contains member objects, 6 call the default heap destructor releases the same memory repeatedly, leading to a memory access exception. 7 8 The solution: a custom copy constructor for a pointer member, 9 to open up another piece of heap memory with the new keyword, stored pointer member copy of the object. 10 * / . 11 class Student 12 is { 13 is public : 14 15 Student ()} { 16 // Default destructor 17 / * 18 Student( Student &stu) 19 { 20 m_age = stu.m_age; 21 p = stu.p; 22 } 23 */ 24 25 //自定义析构函数 26 Student(const Student &stu) 27 { 28 m_age = stu.m_age; 29 p = new int(*stu.p); 30 } 31 32 void showStudent() 33 { 34 cout << m_age << endl;; 35 * P << << COUT endl; 36 COUT << "" << endl; 37 [ } 38 is // Private: 39 int m_age; 40 int * P; 41 is 42 is }; 43 is 44 is int main () 45 { 46 is int A = . 6 ; 47 // Student S1 (10, & A) an erroneous operation, since the destructor defined, the compiler will not provide a default constructor to initialize general; 48 Student S1; 49 s1.m_age = 10 ; 50 s1.p & A = ; 51 is 52 is Student S2 = S1; 53 is s1.showStudent (); 54 is s2.showStudent (); 55 56 is System ( " PAUSE " ); 57 is return 0 ; . 5 // Constructor
Constructor - deep and shallow copy copy
Guess you like
Origin www.cnblogs.com/rtblogs/p/12001246.html
Recommended
Ranking