c++ --类中的动态内存管理、深拷贝

知识点:

1. 深拷贝

  类中含有指针成员时,需要显式定义构造函数实现深拷贝。

2. 类中的动态内存管理

  保证类的析构函数被调用。

一切都在代码中:

 1 #include <iostream>
 2 #include <cstring>
 3 #include <memory>
 4 using namespace std;
 5 
 6 /*类含有指针成员时:需要拷贝构造函数实现深拷贝*/
 7 class Test
 8 {
 9 public:
10     Test():p_str(nullptr),str_len(0)
11     {cout<<"执行默认构造函数";};
12     Test(const char *str);
13     ~Test()
14     {
15         cout<<"执行析构函数"<<endl;
16         delete p_str;
17         cout<<"析构完成"<<endl;
18     };
19 private:
20     char *p_str;    //指针成员
21     size_t str_len;
22 };
23 //拷贝构造函数实现深拷贝
24 Test::Test(const char *str)
25 {
26     cout<<"执行拷贝构造函数"<<endl;
27     str_len=strlen(str);
28     p_str=new char[str_len+1];
29     strcpy(p_str,str);
30 }
31 
32 //返回指向Test的指针
33 Test* createTest()
34 {
35     char c[]="hello";
36     Test *p_test=new Test(c);
37     return p_test;
38 }
39 //采用只能指针shared_ptr
40 shared_ptr<Test> createTest1()
41 {
42     char c[]="hello";
43     shared_ptr<Test> p_test=make_shared<Test>(c);
44     return p_test;
45 }
46 
47 //自动析构
48 int main()
49 {
50     char *c="hello";
51     Test test(c);
52 
53     return 0;
54 }
55 
56 //需手动delete
57 int main()
58 {
59     Test* p_test=createTest();
60     delete p_test;   //delete调用析构函数
61 
62     //shared_ptr<Test> p_test=createTest1();   //智能指针可以自动释放
63 
64     return 0;
65 }
66 
67 /*为了避免因各种情况遗漏delete,造成内存泄漏,可使用
68 "Effective C++"中条款13和18中提到的方法解决问题。
69 */
70 
71 //以对象管理资源:把资源放进对象内(条款13),
72 //并让接口容易被正确使用(条款18)
73 int main()
74 {
75     //Test* p_test=createTest();
76     //delete p_test;   //delete调用析构函数
77 
78     shared_ptr<Test> p_test=createTest1();   //智能指针可以自动释放
79 
80     return 0;
81 }

   新 type 与内置类型保持一致性!!!


原文地址:https://www.cnblogs.com/cygalaxy/p/7107475.html