深拷贝和浅拷贝

https://www.cnblogs.com/always-chang/p/6107437.html

先考虑一种情况,对一个已知对象进行拷贝,编译系统会自动调用一种构造函数——拷贝构造函数,如果用户未定义拷贝构造函数,则会调用默认拷贝构造函数

//main.cpp

#include <iostream>

#include "student.h"

int main()

{

         Student s1;

         Student s2(s1);//Student s2 = s1;//复制对象

         return 0;

}

//student.h

#ifndef STUDENT_H

#define STUDENT_H

class Student

{

         private:

               int num;

               char *name;

         public:

                Student();

                ~Student();

};

#endif

//student.cpp

#include "student.h"

#include <iostream>

using namespace std;

Student::Student()

{

       name = new char(20);  cout << "Student" << endl;

}

Student::~Student()

{

        cout << "~Student " << (int)name << endl;

        delete name; name = NULL;

}

执行结果:调用一次构造函数,调用两次析构函数,两个对象的指针成员所指内存相同,这会导致什么问题呢?

name指针被分配一次内存,但是程序结束时该内存却被释放了两次,会造成内存泄漏问题!

这是由于编译系统在我们没有自己定义拷贝构造函数时,会在拷贝对象时调用默认拷贝构造函数,进行的是浅拷贝对指针name拷贝后会出现两个指针指向同一个内存空间。

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

 自己定义拷贝构造函数:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

//student.h

#ifndef STUDENT_H

#define STUDENT_H

class Student

{

       private:

             int num;

             char *name;

      public:

              Student();//构

              ~Student();//析构函数

               Student(const Student &s);//拷贝构造函数,const防止对象被改变

};

#endif

 

//student.cpp

#include "student.h"

#include <iostream>

#include <string.h>

using namespace std

Student::Student()

{

      name = new char(20);

      cout << "Student " << endl;

}

Student::~Student()

{

         cout << "~Student " << (int)name << endl;

         delete name;

         name = NULL;

}

Student::Student(const Student &s)

{

         name = new char(20);

         memcpy(name, s.name, strlen(s.name));

         cout << "copy Student " << endl;

}

执行结果:调用一次构造函数,一次自定义拷贝构造函数,两次析构函数。两个对象的指针成员所指内存不同。 

总结:浅拷贝只是对指针的拷贝,拷贝后两个指针指向同一个内存空间,深拷贝不但对指针进行拷贝,而且对指针指向的内容进行拷贝,经深拷贝后的指针是指向两个不同地址的指针。

再说几句:

当对象中存在指针成员时,除了在复制对象时需要考虑自定义拷贝构造函数,还应该考虑以下两种情形:

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

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值