浅拷贝:编译器自动添加的拷贝构造函数进行的值拷贝。
深拷贝:在堆区重新申请空间进行拷贝操作。
浅拷贝可能面临重复释放空间的错误,深拷贝则可避免。
#include <iostream>
using namespace std;
class Person{
public:
Person(){
cout << "默认构造函数" << endl;
}
Person(int age, int height){
m_age = age;
m_height = new int(height);
cout << "有参构造函数" << endl;
}
Person(const Person &p){
m_age = p.m_age;
// 浅拷贝操作
//m_height = p.m_height;
// 深拷贝操作
m_height = new int(*p.m_height);
cout << "拷贝构造函数" << endl;
}
~Person(){
if(m_height != NULL){
delete m_height;
m_height = NULL;
}
cout << "析构函数" << endl;
}
int m_age;
int* m_height;
};
void test(){
Person p1(18, 160);
cout << p1.m_age << " " << *p1.m_height << endl;
Person p2(p1);
cout << p2.m_age << " " << *p2.m_height << endl;
}
int main() {
test();
return 0;
}