深拷贝与浅拷贝的异同

默认的拷贝构造函数

  如果一个类中没有定义拷贝构造函数,则系统会自动提供一个默认拷贝构造函数,用来根据已有对象创建新对象;我们要知道这个默认的拷贝构造函数采用的是"浅拷贝“,并非"深拷贝“

深拷贝与浅拷贝的区别

浅拷贝只是对指针的拷贝,拷贝后两个指针指向同一个内存空间;深拷贝不仅对指针拷贝,对指针指向的内容也进行拷贝,深拷贝后的两个指针分别指向不同的内存空间

浅拷贝带来的问题

1. 浅拷贝后的两个指针指向同一内存空间,在对象块结束,调用析构函数时,会造成同一块资源析构两次,即delete同一块内存两次,造成程序崩溃
2. 浅拷贝的两个指针,任何一方的改变都会影响到另一方

编码看一下两者的区别
浅拷贝:

#include <iostream>
using namespace std;

class Student
{
	public:
	    Student();
	    ~Student();
	private:
	    int num;
	    char *name;
};

Student::Student()
{
	name = new char('a');
	cout << "name=" << *name << endl;
	cout << "Constructor called" << endl;
}
Student::~Student()
{
	delete name;
	cout << "Destructor called" << endl;
}
int main()
{
	//花括号让s1、s2变为局部变量,方便测试
	{ 
		Student s1;
		Student s2(s1);
	}
	system("pause");
	return 0;
}

在这里插入图片描述
在这里插入图片描述
由以上的调试结果可知,程序运行出错,下面我们自定义个深拷贝构造函数

深拷贝

#include <iostream>
using namespace std;

class Student
{
	public:
	    Student();
	    ~Student();
		Student(const Student &s);
	private:
	    int num;
	    char *name;
};

Student::Student()
{
	name = new char('a');
	cout << "name=" << *name << endl;
	cout << "Constructor called" << endl;
}
Student::~Student()
{
	delete name;
	cout << "Destructor called" << endl;
}
Student::Student(const Student &s) //自定义拷贝构造函数
{
	name = new char('a');
	memcpy(name, s.name, sizeof(s.name));
	cout << "Copy constructor called" << endl;
}
int main()
{
	//花括号让s1、s2变为局部变量,方便测试
	{ 
		Student s1;
		Student s2(s1);
	}
	system("pause"![在这里插入图片描述](https://img-blog.csdnimg.cn/20190401181017895.png));
	return 0;
}

在这里插入图片描述
一切正常

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值