#include <iostream>#include<string>#include<assert.h>using namespacestd; //declaring a string copy functionChar* MYSTRCPY (Char* STR1,Const Char*str2);classcperson{Char*M_pname; Public: CPerson (Char*pName) {cout<<"Common Constructors"<<Endl; M_pname=New Char[Strlen (PName) +1]; if(m_pname) {mystrcpy (m_pname, pName); } }//copy constructor, make only bit-mode copy, i.e. shallow copy//CPerson (CPerson &p)// {//m_pname = p.m_pname; // } //Deep Copy ConstructorsCPerson (CPerson &p) {cout<<"Deep Copy Constructors"<<Endl; M_pname=New Char[Strlen (P.m_pname) +1]; if(m_pname) {mystrcpy (m_pname, p.m_pname); } } ~CPerson () {cout<<" Destructors"<<Endl; Delete[] m_pname; }};intMain () {CPerson P1 ("Hello"); CPerson P2 (p1); //shallow copy, call shallow copy constructor, P1.m_pname and P2.m_pname pointers point to an address at the same time//when destructors are called, m_pname pointers are deleted two times, causing errors,//so to solve this problem with a deep copy return 0;}//the realization of mystrcpyChar* MYSTRCPY (Char* STR1,Const Char*str2) { Char* p =str1; ASSERT (str1! = NULL && str2! =NULL); while(*str2) { *p = *str2; P++; STR2++; } P=NULL; returnstr1;}
As a beginner, just start to look at the video, and then copy the code, Mengmengdongdong on the past, however, back to the original basic knowledge, to understand its "why."
Can't sleep, review the basics of C + + basics (deep copy and shallow copy)