Copy constructor (deep copy vs light copy)
The initialization between class objects is completed by the copy constructor of the class. It is a special constructor that uses a known object to initialize another object. If a copy constructor is not explicitly declared in the class, the compiler automatically generates a default copy constructor, which completes the bitwise copy between objects. Bit copy is also called the shortest copy.
1. Copy the Definition Format of the constructor
Class Name: copy the constructor name (Class Name & reference name)
For example:
Tdate: tdate (tdate & D); // a reference to an object
Cstring (const cstring & stringsrc); // a const Object Reference
2. In the following three cases, you need to use the copy initialization constructor:
1) indicates that when another object is initialized by one object, such as cdate day3 (D1 );
2) when an object is passed to a function as a real parameter, such as fun (cdate Day );
3) when an object is used as the return value of a function to create a temporary object.
Shortest copy and deep copy
In some situations, the member variables in the class need to dynamically open up heap memory. If bit copy is implemented, that is, the value in the object is completely copied to another object, such as a = B. If a member variable pointer in B has applied for memory, the member variable in a also points to the same memory. This causes a problem: when B releases the memory (such as the destructor), the pointer in A is a wild pointer and a running error occurs.
Deep copy and shallow copy can be simply understood as: If a class has resources, when the objects of this class are copied, the resources are re-allocated. This process is a deep copy, and vice versa, if no resources are re-allocated, it is a small copy. The following is an example of deep copy.
#include "stdafx.h"#include <iostream>#include <string>#include <stdio.h>using namespace std;class CClass{public:CClass (char *cName="",int snum=0);~CClass(){cout<<"析构班级:"<<pname<<endl;delete pname;}void Print();private:char *pname;int num;};CClass::CClass(char *cName,int snum){int length = strlen(cName);pname = new char[length+1];if (pname!=0) //pname!=NULLstrcpy(pname,cName);num=snum;cout<<"创建班级:"<<pname<<endl;}void CClass::Print(){cout<<pname<<"班的人数为:"<<num<<endl;}int _tmain(int argc, _TCHAR* argv[]){CClass c1("计算机061班,56);CClass c2 (c1);c1.Print();c2.Print(); //system("pause");return 0;}
C1 and C2 memory allocation (deep copy)
CClass(CClass &p); //自定义拷贝构造函数声明//添加自定义拷贝构造函数CClass::CClass(CClass &p){pname = new char[strlen(p.pname )+1];if (pname!=0)strcpy(pname,p.pname);num=p.num ;cout<<"创建班级的拷贝:"<<pname<<endl;}
Running result:
Create a class: Class 061
Create a copy of the class: Class 061
The number of students in the 061 computer class is 56.
The number of students in the 061 computer class is 56.
Analysis class: Class 061
Analysis class: Class 061
Copy constructor (deep copy vs light copy)