Home > Back-end >  Consult c bosses a deep copy problem!!!
Consult c bosses a deep copy problem!!!

Time:09-17

# include
using namespace std;

//deep and shallow copy

The class Person
{
Public:

The Person (s)
{

Cout & lt;
}

The Person (int the age, int height)
{

M_Age=age;
M_Height=new int (height);
Cout & lt; <"Person has a constructor calls refs" & lt;
}
The Person (const Person & amp; P)
{

Cout & lt; <"The Person copy constructor calls" & lt; M_Age=p. _Age;
//m_Height=p. _Height;//the default compiler implementation is this line of code
//deep copy operations
M_Height=new int (* p. _Height);
}

To the Person (s)
{
//destructor code, the heap area set up data do release operation
If (m_Height!=NULL)
{
The delete m_Height;
M_Height=NULL;

}
Cout & lt; <"Person destructor call" & lt;
}

Int m_Age;
Int * m_Height;


};

Void test501 ()
{
The Person p1 (18160);

Cout & lt; <"P1 age for" & lt;
The Person p2 (p1);

Cout & lt; <"P2 age for" & lt; }


Int main ()
{
Test501 ();





system("pause");

return 0;


}


Grammar to compile successfully, detailed debugging can also print, when an error is a memory

CodePudding user response:

Code is no problem, please to recompile

CodePudding user response:

You this is clear, the default copy is the pointer is assigned to the new object, deep copy need to apply for memory, put the address is assigned to a new object
  • Related