深浅拷贝以及拷贝构造应用于函数的参数返回值副本机制

 1 #include<iostream>
 2 
 3 using namespace std;
 4 
 5 class myclass
 6 {
 7 public:
 8     
 9     myclass()
10     {
11         cout << "myclass create" << endl;
12     }
13 
14     myclass(const myclass & my)
15     {
16         cout << "myclass copy" << endl;
17     }
18 };
19 
20 
21 void show(myclass & my)// 非参数也有副本机制
22 {
23 
24 }
25 
26 myclass get()// 函数的返回值有副本机制 调用拷贝构造实现拷贝
27 {
28     myclass a;
29     return a;
30 }
31 
32 
33 int main()
34 {
35     myclass my1;
36     myclass my2(my1);
37     show(my2);
38     get();
39 
40     std::cin.get();
41     return 0;
42 }
43 
44 //---------------------------------------------------------
45 
46 /* 深浅拷贝 */
47 
48 
49 #include<iostream>
50 #include<cstring>
51 
52 using namespace std;
53 
54 class mystring
55 {
56 public:
57     char *p;
58     int n;
59     mystring(int n,char *str)
60     {
61         p = new char[n];// 分配内存
62         strcpy(p,str);// 拷贝
63     }
64 
65     ~mystring()
66     {
67         delete []p;// 释放内存
68     }
69     
70     // 深拷贝
71     mystring(const mystring & my)
72     {
73         int length = strlen(my.p)+1;
74         this->p = new char[length];
75         strcpy(this->p,my.p);// 拷贝内存
76     }
77     
78 
79 };
80 
81 // 默认的拷贝构造是浅拷贝
82 int main()
83 {
84     mystring str1(20,"tasklist");
85     cout << str1.p << endl;
86     
87     mystring str2(str1);
88     str1.~mystring();
89     cout << str2.p << endl;
90 
91 
92     std::cin.get();
93     return 0;
94 }

 

posted on 2015-06-06 09:12  Dragon-wuxl  阅读(285)  评论(2)    收藏  举报

导航