The copy constructor is called when the object of the class needs to be copied. The copy constructor is called in the following cases:
(1) An object is passed into the function body in the way of value passing
(2) An object is returned from the function in the way that the value is passed
(3) An object needs to be initialized by another object.
Deep if a class has resources, when the object of this class has a replication process, the resource is redistributed, the process is a deep copy, and conversely, no redistribution of resources, is a shallow copy.
If a shallow copy is applied, the value in the object is completely copied to another object, such as A=b. At this point, if a member variable pointer in B has already applied for memory, that member variable in a also points to the same piece of memory. There is a problem: when B releases the memory (for example, a destructor), a pointer inside a is a wild pointer, and a run error occurs.
1 //Shallow Copy2#include <iostream>3 using namespacestd;4 5 classCexample {6 Private:7 intA;8 Public:9Cexample (intb)Ten{a=b;} One ACexample (Constcexample&C) - { -A=C.A; the } - voidShow () - { -cout<<a<<Endl; + } - }; + A intMain () at { -Cexample A ( -); -Cexample b=A; - b.show (); - return 0; -}
1 //Deep Copy2#include <iostream>3 using namespacestd;4 classCA5 {6 Public:7CA (intBChar*CStr)8 {9A=b;TenStr=New Char[b]; One strcpy (STR,CSTR); A } -DAOConstca&C) - { theA=C.A; -Str=New Char[A]; - if(str!=0) - strcpy (STR,C.STR); + } - voidShow () + { Acout<<str<<Endl; at } -~CA () - { - Deletestr; - } - Private: in intA; - Char*str; to }; + - intMain () the { *CA A (Ten,"hello!"); $CA b=A;Panax Notoginseng b.show (); - return 0; the}
About C + + copy constructors