天天看点

C++深拷贝与浅拷贝的区别

    博主近来在找实习,需要准备面试,在此总结一些C++常考的知识点。

1.深拷贝与浅拷贝

1.当函数的参数为对象时,实参传递给形参的实际就是实参的一个拷贝对象,系统自动通过调用拷贝构造函数来实现。

2.当函数的返回值为一个对象时,该对象实际上是函数内对象的一个拷贝,用于返回函数调用处。

定义类student,student s1=new student;student s2=s1

//Student.cpp
           
#include "Student.h"
#include <iostream>
using namespace std;
Student::Student(void)
{
	name =new char(20);
	cout<<"student build:"<<endl;

}
Student::Student(const Student &s1)
{
	name = new char(20);
	memcpy(name, s1.name, strlen(s1.name));
    cout << "copy Student " << endl;
}

Student::~Student(void)
{
	cout<<"~Student:"<<(int)name<<endl;
	delete name;
	name = NULL;
}
           
//Student.h
           
#pragma once
class Student
{
public:
	Student(void);
	Student(const Student &s1);

	~Student(void);
private:
	int a;
	char *name;
};
           
//main.cpp
#include <stdio.h>
#include <iostream>
#include "Student.h"
using namespace std;
int main()
{
	Student s1;
	Student s2(s1);
	cout<<sizeof(s1)<<endl;
	//s2=s1;
	return 0;
}
           

在执行s2=s1时就会调用拷贝构造函数。如果没有定义拷贝构造函数,系统会在拷贝对象是调用默认拷贝构造函数,进行浅拷贝!浅拷贝对指针拷贝后会出现两个指针指向同一内存空间的情况。

所以,在对含有指针成员的对象进行拷贝时,必须要自己定义拷贝构造函数,使拷贝后的对象指针成员有自己的内存空间,即进行深拷贝,这样就避免了内存泄漏发生。

浅拷贝 —-只是拷贝了基本类型的数据,而引用类型数据,复制后也是会发生引用,我们把这种拷贝叫做“(浅复制)浅拷贝”,换句话说,浅复制仅仅是指向被复制的内存地址,如果原地址中对象被改变了,那么浅复制出来的对象也会相应改变。

深拷贝 —-在计算机中开辟了一块新的内存地址用于存放复制的对象。

C++深拷贝与浅拷贝的区别

浅拷贝调用一次构造函数,一次默认拷贝构造函数,两次析构函数

深拷贝调用一次构造函数,一次定义的构造函数,两次析构函数

附:调用sizeof(s1)=8,可见对象里包括int 与一个char*的指针,分配的内存并不算在对象的大小里。