听说浅拷贝与深拷贝是面试经典问题,也是常见的一个坑

  • 浅拷贝:简单的赋值拷贝操作

  • 深拷贝:在堆区重新申请空间,进行拷贝操作

总结写在前面应该不会有问题吧,不会吧不会吧

总结: 如果属性有在堆区开辟的,一定要自己提供拷贝构造函数,防止浅拷贝带来的问题

浅拷贝

举个栗子:

我是 氷羽藍汐,但我还有个名字叫张三,虽然有两名字,但都是我一个人。

所以,不论谁脑瘫也好骨折也罢,都是我倒霉

代码示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include<iostream>
using namespace std;

class Person{
public:
Person(int age,int height) {
cout << "Person的有参构造函数调用" << endl;
m_Age = age;
m_Height = new int(height);
}
Person(const Person& p) {
cout << "Person的拷贝构造函数调用" << endl;
m_Height = p.m_Height;//编译器默认实现就是这行代码
m_Age = p.m_Age
}
~Person() {
cout << "Person的析构函数调用" << endl;
if (m_Height != NULL) {
delete m_Height;
m_Height = NULL;
}
}
int m_Age;
int* m_Height;
};

int main() {
Person p1(18,160);
cout << "p1的年龄" << p1.m_Age << endl << "身高为:" << *p1.m_Height << endl;

Person p2(p1);
cout << "p2的年龄" << p2.m_Age << endl << "身高为:" << *p1.m_Height << endl;
}

深拷贝

再举个栗子:

我是 氷羽藍汐,正在进行一个实验,以我自己为模板,进行克隆实验,这个克隆人叫 张三

因此,不论是氷羽藍汐还是张三 脑瘫或骨折,都不会影响到另外一个人

代码示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include<iostream>
using namespace std;

class Person{
public:
Person() {
cout << "Person的默认构造函数调用" << endl;
}
Person(int age,int height) {
cout << "Person的有参构造函数调用" << endl;
m_Age = age;
m_Height = new int(height);
}
Person(const Person& p) {
cout << "Person的拷贝构造函数调用" << endl;
m_Height = new int(*p.m_Height);
//如果不用深拷贝在堆区创建新内存,会导致浅拷贝带来的重复释放堆区问题
m_Age = p.m_Age;
}
~Person() {
cout << "Person的析构函数调用" << endl;
if (m_Height != NULL) {
delete m_Height;
m_Height = NULL;
}
}
int m_Age;
int* m_Height;
};

int main() {
Person p1(18,160);
cout << "p1的年龄" << p1.m_Age << endl << "身高为:" << *p1.m_Height << endl;

Person p2(p1);
cout << "p2的年龄" << p2.m_Age << endl << "身高为:" << *p1.m_Height << endl;
}