29)深拷贝和浅拷贝

1)浅拷贝,就是单单的将数值拷过去,包括你的指针指向

2)那么就有一个问题了(浅拷贝)

  

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 
 5 
 6 class Teacher{
 7 public:
 8     Teacher(int id,char *name)
 9     {
10         this->id=id;
11         int len=strlen(name);
12 
13         this->name=(char*)malloc(len+1);
14         strcpy(this->name,name);
15     }
16     Teacher(const Teacher &another)
17     {
18         this->name=another.name;
19         this->id=another.id;
20     }
21     ~Teacher()
22     {
23         cout<<"Teacher的析构函数"<<endl;
24         if(this->name!=NULL)
25         {
26             free(this->name);
27             this->name=NULL;
28         }
29         
30     }
31 private:
32     char *name;
33     int id;
34 
35 };
36 //为啥有这个函数,因为想要我实例化的对象好 析构掉,只要我调用了这个函数,之后就会把这个函数里的对象给析构掉
37 void hanshu()
38 {
39     Teacher t1(1,"王超");
40     Teacher t2=t1;
41 }
42 int main()
43 {
44     hanshu();
45 
46 //后面,那个hanshu()里的对象就被袭析构掉了
47     return 0;
48 }

    

  这个的关系类图是:

    

    然后就是那个t2 就是这样的。

    

     但是我调用完 hanshu()后,先析构t2    那么那块对内存被回收了

     然后,我又回收t1    那个t1的name不是空   还是调用那个free函数,但是  那块内存已经被回收了,所以就有了错误,系统就崩掉了

 

这个是浅拷贝带来的问题

然后,就有可深拷贝,来避免这个问题

需要一个显式的深构造函数,来完成深构造函数

只要你的类成员中有一个指针,就需要 提供一个手动深构造函数,来完成深拷贝动作。

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 
 5 
 6 class Teacher{
 7 public:
 8     Teacher(int id,char *name)
 9     {
10         this->id=id;
11         int len=strlen(name);
12 
13         this->name=(char*)malloc(len+1);
14         strcpy(this->name,name);
15     }
16     //新加的拷贝构造函数
17     Teacher(const Teacher &another)
18     {
19         id=another.id;
20         //深拷贝动作
21         int len=strlen(another.name);
22         name=(char*)malloc(len+1);
      strcpy(name,another.name);
23 } 24 25 ~Teacher() 26 { 27 cout<<"Teacher的析构函数"<<endl; 28 if(this->name!=NULL) 29 { 30 free(this->name); 31 this->name=NULL; 32 } 33 34 } 35 private: 36 char *name; 37 int id; 38 39 }; 40 void hanshu() 41 { 42 Teacher t1(1,"王压抑"); 43 Teacher t2=t1; 44 } 45 int main() 46 { 47 hanshu(); 48 return 0; 49 }

 

 

然后就变成了:

  

 

posted @ 2018-01-03 14:02  小油菜1  阅读(127)  评论(0编辑  收藏  举报