包含动态内存分配的类需要自定义拷贝构造函数。
无定义默认为浅拷贝,此时参数对象和创建对象的指针成员指向同一块内存,调用二者的析构函数时第一对象调用释放内存成功,第二个对象会再次进行释放内存,此时运行时出错double free
故:应定义,且为深拷贝
浅拷贝实例代码:
1 #include<iostream> 2 3 class A 4 { 5 public: 6 A() 7 { 8 std::cout << "constructor is called" << std::endl; 9 n = new int[10]; 10 n[0] = 1; 11 } 12 // 默认拷贝构造函数 13 /*A(const A &t) 14 { 15 std::cout << "copy constructor is called" << std::endl; 16 n = t.n; 17 } 18 */ 19 20 ~A() 21 { 22 std::cout << "destructor is called" << std::endl; 23 delete n; 24 } 25 26 void get() { std::cout << "n[0]: " << n[0] << std::endl; } 27 private: 28 int *n; 29 }; 30 31 int main(void) 32 { 33 A a; 34 A b(a); 35 b.get(); 36 37 return 0; 38 }
编译运行后结果:
深拷贝实例代码:
1 #include<iostream> 2 #include<string.h> 3 4 class A 5 { 6 public: 7 A() 8 { 9 std::cout << "constructor is called" << std::endl; 10 n = new int[10]; 11 n[0] = 1; 12 } 13 // 深拷贝 14 A(const A &t) 15 { 16 std::cout << "copy constructor is called" << std::endl; 17 n = new int[10]; 18 memcpy(n, t.n, 10); 19 } 20 21 ~A() 22 { 23 std::cout << "destructor is called" << std::endl; 24 delete n; 25 } 26 27 void get() { std::cout << "n[0]: " << n[0] << std::endl; } 28 private: 29 int *n; 30 }; 31 32 int main(void) 33 { 34 A a; 35 A b(a); 36 b.get(); 37 38 return 0; 39 }
编译运行结果:
时间: 2024-09-29 19:38:33