Both shallow and deep copies are relative copy constructors.
The following code implements a shallow copy,
1#include <stdio.h>2#include <iostream>3#include <string>4 using namespacestd;5 6 classA7 {8 Public :9AintA=0): M_num (a) {};TenAConstA &arr); One intset_num (); A Private: - intM_num; - }; the -A::a (ConstA &arr) - { -m_num=Arr.m_num; + } - intA::set_num () + { A returnM_num; at } - intMain (void) - { -A arr1 (5); - A arr2 (arr1); -cout <<"arr1="<<arr1.set_num () <<endl<<"arr2="<<arr2.set_num () <<Endl; in return 0; -}
Add one more class member pointer variable,
1#include <stdio.h>2#include <iostream>3#include <string>4 using namespacestd;5 6 classA7 {8 Public :9AintA=0)Ten { Onecout <<"A"<<Endl; Am_num=A; -M_a=New int[M_num]; - }; theAConstA &arr); - intset_num (); -~A (); - Private: + intM_num; - int*m_a; + }; A atA::a (ConstA &arr) - { -cout <<"&a"<<Endl; -M_a=arr.m_a; -m_num=Arr.m_num; - } in intA::set_num () - { to returnM_num; + } -a::~A () the { *cout <<"~a"<<Endl; $ Delete[]m_a;Panax Notoginseng } - intMain (void) the { +A arr1 (5); A A arr2 (arr1); thecout <<"arr1="<<arr1.set_num () <<endl<<"arr2="<<arr2.set_num () <<Endl; + return 0; -}
The above program copy constructor copies the object's pointer address to the current object's pointer address,
When executing to a destructor, think there are two objects, not to be deleted two times, when running the first time without problems,
When you run the second program, it crashes.
It's going to be a deep copy to solve this problem.
1#include <stdio.h>2#include <iostream>3#include <string>4 using namespacestd;5 6 classA7 {8 Public :9AintA=0)Ten { Onecout <<"A"<<Endl; Am_num=A; -M_a=New int[M_num]; - }; theAConstA &arr); - intset_num (); - voidset_m_a (); -~A (); + Private: - intM_num; + int*m_a; A }; at - voida::set_m_a () - { - for(intI=0; i<m_num;i++) - { -m_a[i]=i; incout <<"m_a["<<i<<"]="<<m_a[i]<<Endl; - } to + } -A::a (ConstA &arr) the { *m_num=Arr.m_num; $cout <<"&a"<<Endl;Panax NotoginsengM_a=New int[Arr.m_num]; - for(intI=0; i<arr.m_num;i++) the { +m_a[i]=Arr.m_a[i]; A } the + - } $ intA::set_num () $ { - returnM_num; - } thea::~A () - {Wuyicout <<"~a"<<Endl; the Delete[]m_a; - } Wu intMain (void) - { AboutA arr1 (5); $ A arr2 (arr1); -cout <<"arr1="<<arr1.set_num () <<endl<<"arr2="<<arr2.set_num () <<Endl; -cout <<"arr1.m_a="; Arr1.set_m_a (); -cout<<Endl; Acout <<"arr2.m_a="; Arr2.set_m_a (); + return 0; the}
The assignment between this object is not an assignment between the addresses, nor is it freed two times in the same block memory.
Deep shallow copy and deep copy. Beginners ' Notes