STL

下面这个例子,在涉及类 类型 的复制拷贝的时候,加入其成员变量中有 指针时候,该如何处理?

 1 #include<iostream>
 2 #include<vector>
 3 
 4 using namespace std;
 5 
 6 class Person
 7 {
 8 public:
 9     Person() 
10     {
11         cout << "调用无参数默认构造" << endl;
12     };
13     Person(char* name, int id)
14     {
15         this->name_ = new char[strlen(name) + 1];// 加一 留给 结束符''
16         strcpy(this->name_, name);
17         this->id_ = id;
18         cout << "调用有参数默认构造" << endl;
19     }
20     Person(const Person& p)
21     {
22         this->name_ = new char[strlen(p.name_) + 1];
23         strcpy(this->name_, p.name_);
24         this->id_ = p.id_;
25         cout << "调用拷贝构造" << endl;
26     }
27     //重载 = 
28     Person& operator=(Person& p)
29     {
30         this->name_ = new char[strlen(p.name_) + 1];
31         strcpy(this->name_, p.name_);
32         this->id_ = p.id_;
33         cout << "调用重载" << endl;
34         return *this;
35     }
36     ~Person()
37     {
38         if (this->name_ !=nullptr)
39         {
40             delete[] this->name_;
41         }
42     }
43 public:
44     char* name_; // 指针容易发生浅层拷贝问题;所以必须添加拷贝构造函数
45     int id_;
46 };
47 
48 void test01()
49 {
50     Person p1("shi", 1); //调用有参数
51     vector<Person> vec;
52     vec.push_back(p1);// 调用拷贝
53 
54     Person p2(p1);//调用拷贝
55     Person p3;//调用无参
56     p3 = p2;//调用重载 = 
57 }
58 
59 int main()
60 {
61     test01();
62     char* a = "shiruiyu";
63     int b = strlen(a);
64     return 1;
65 }

 上述:

strcpy()出现了三次,有参数构造函数、拷贝构造函数、重载= 操作符; 都是深层次拷贝。
原文地址:https://www.cnblogs.com/winslam/p/9444107.html