浅拷贝
系统默认拷贝时,将p1中的height与它指向的地址完全拷贝了一份,在释放时,p2会将这个空间释放,而p1此时地址并不是NULL,但是指向的空间已经被释放了。浅拷贝只是复制了一个地址过去了,两个对象使用的依然是同一个内存空间。
#include <iostream>
using namespace std;
//深拷贝与浅拷贝
class Person {
public:
Person() {}
Person(int age, int height) {
m_Age = age;
m_Height = new int(height);
}
~Person() {
//将堆区开辟的空间关闭
if(m_Height != NULL){
delete m_Height;
m_Height = NULL;
}
}
int m_Age;
int * m_Height;
};
void test01() {
Person p1(18, 180);
cout << "p1的年龄为:" << p1.m_Age << ",身高为:" << *p1.m_Height << endl;
Person p2(p1);
p2.m_Age = 20;
cout << "p2的年龄为:" << p2.m_Age << ",身高为:" << *p2.m_Height << endl;
}
int main() {
test01();
return 0;
}
深拷贝
深拷贝在拷贝的过程中在堆区开辟一个新的空间,并且将*m_Height指向这个空间。深拷贝就是将这个空间又复制一份,再指向这个新的空间。
#include <iostream>
using namespace std;
//深拷贝与浅拷贝
class Person {
public:
Person() {}
Person(int age, int height) {
m_Age = age;
m_Height = new int(height);
}
Person(const Person &p) {
m_Age = p.m_Age;
// m_Height = p.m_Height;//编译器默认实现的是这样的代码,只是将地址赋给了p2
int *newHeight = new int(*p.m_Height);
m_Height = newHeight;
}
~Person() {
//将堆区开辟的空间释放
if (m_Height != NULL) {
delete m_Height;
m_Height = NULL;
}
}
int m_Age;
int *m_Height;
};
void test01() {
Person p1(18, 180);
cout << "p1的年龄为:" << p1.m_Age << ",身高为:" << *p1.m_Height << endl;
Person p2(p1);
cout << "p2的年龄为:" << p2.m_Age << ",身高为:" << *p2.m_Height << endl;
}
int main() {
test01();
return 0;
}