- 在未定义拷贝构造函数时,系统会调用默认的拷贝构造函数---即浅拷贝,它能够完成成员的一一复制。当数据成员中没有指针时,浅拷贝是可行的;当数据成员中有指针时,如果采用简单的浅拷贝,则两个类中的两个指针将指向同一个地址,当生命周期结束时,会调用两次析构函数,而指针成员变量只有一块空间,释放一次后,另一个指针所指向的空间就不存在了,从而导致指针悬挂;
- 总而言之,当数据成员中有指针时,必须要用深拷贝;
- 解决方案:自定义拷贝函数,形参为对象的引用
class(const class& other)
测试代码
#include <iostream> using namespace std; class Person { public: Person() { cout << "默认构造函数的调用\n"; } Person(int age,int height) { cout << "有参构造函数的调用\n"; m_age = age; m_height = new int(height); } //拷贝函数(形参为对象的引用) Person(const Person& other) //形参为对象的引用 { cout << "拷贝构造函数的调用" << endl; m_age = other.m_age; m_height = new int(*other.m_height); } ~Person() { if (m_height != NULL) { delete m_height; m_height = NULL; } cout << "析构函数的调用\n"; } int m_age; int* m_height; }; int main() { Person a(10,190); Person b(a); //类参数含指针的拷贝,拷贝函数(形参为对象的引用) cout << "a的年龄为:" << a.m_age << " a的身高为:" << *a.m_height << " a的地址为:"<< a.m_height <<endl; cout << "b的年龄为:" << b.m_age << " b的身高为:" << *b.m_height << " b的地址为:"<< b.m_height <<endl; return 0; }