C++面试题(深拷贝和浅拷贝的区别)

概括的说:浅拷贝是让两个指针指向同一个位置,而深拷贝是让另一个指针自己再开辟空间。

#include<bits/stdc++.h>
using namespace std;
class Student {
	int name;
	int* p;
public:
	~Student() {
		//cout << p << endl;
		delete p ; //delete只能和New连用,这里p也是New出来的。
		cout << "删除完毕" << endl;
	}
	Student() {
		p = new int();
	}
};
int main() {
	Student a=*(new Student());
	Student b(a); //拷贝复制过来 这是浅拷贝 指向一个位置
	return 0;
}

运行时报错:
在这里插入图片描述

我们可以看到只执行了一个删除操作,这是为什么?

因为a和b都指向同一个位置,当程序结束要调用析构函数时,会出现重复调用,多次delete所以报错。

归根结底是因为我们让两个指针指向了同一个位置,那么怎么改呢?

#include<bits/stdc++.h>
using namespace std;
class Student {
	int name;
	int* p;
public:
	~Student() {
		//cout << p << endl;
		delete p ; //delete只能和New连用,这里p也是New出来的。
		cout << "删除完毕" << endl;
	}
	Student() {
		p = new int();
	}
	Student(const Student& a) {
		name = a.name;
	}
};
int main() {
	Student a=*(new Student());
	Student b(a); //拷贝复制过来 这是浅拷贝 指向一个位置
	return 0;
}

在这里插入图片描述

删除完毕,自定义了拷贝复制函数,又开辟了空间(深拷贝)。

其实我们不必去纠结这个问题,c++这些细节十分晦涩。这里delete出现问题也是因为我们自定义了析构函数,在里面自己加了delete,如果我们不加delete,让它执行默认的析构函数。在这里插入图片描述仍然正确,析构函数delete的时候会现在指针指向的位置是否有指针指向(智能指针),我们正常情况下不需要去写析构函数,所以也不会出现这个错误。

正在学习c++,如有错误,欢迎指出。

发布了50 篇原创文章 · 获赞 67 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_41033366/article/details/103042966