Computer Language/C++

[C++] Shallow Copy & Deep Copy

정우섭 2020. 6. 2. 22:58

Shallow Copy

 

#include <iostream>
#include <cstring>

using namespace std;

class Person
{
private:
	char* name;
	int age;
public:
	Person(char *myname, int myage)
	{
		int len = strlen(myname) + 1;
		name = new char[len];
		strcpy(name, myname);
		age = myage;
	}
	void ShowPersonInfo() const
	{
		cout << "name: " << name << endl;
		cout << "age: " << age << endl;
	}
	~Person()
	{
		delete[] name;
		cout << "called destructor" << endl;
	}
};


int main()
{
	Person man1("Woo Seop Jung", 21);  //let's say man1.*name point's address '0xAA'
	Person man2("Elon Musk", 48);      //let's say man2.*name point's address '0xBB'
	man2 = man1;		//shallow copy, call default constructor. So it just copys the value of member.
	man1.ShowPersonInfo();
	man2.ShowPersonInfo();	//error occurs

	return 0;
}

 

This code has a critical error.

 

Let's see the following picture.

 

<Before Copy>

 

This is heep memory after compiling line35.

 

After Copy

But while compiling line36 the first problem occurs.

 

The memory of string "Elon Musk" in address '0xBB' is not connected to any pointers.

 

So it becomes the leak of memory.

 

If the code is not managing memory, you have no idea to access '0xBB'.

 

And also there's another big problem, at the end of the code the default destructors will be called.

 

When 'man1' destructor will get rid of "Woo Seop Jung" memory.

 

In memory space '0xAA' there's no more string to be destructed by 'man2' destructor.

 

Because of these errors, this code is extremely dangerous to compile.

 

So in this kind of situation, 'Deep Copy' is used.

 

 

 

Deep Copy

 

#include <iostream>
#include <cstring>

using namespace std;

class Person
{
private:
	char* name;
	int age;
public:
	Person(char *myname, int myage)
	{
		int len = strlen(myname) + 1;
		name = new char[len];
		strcpy(name, myname);
		age = myage;
	}
	Person(const Person& copy) : age(copy.age)
	{
		int len = strlen(copy.name) + 1;
		name = new char[len];
		strcpy(name, copy.name);
	}
	void ShowPersonInfo() const
	{
		cout << "name: " << name << endl;
		cout << "age: " << age << endl;
	}
	~Person()
	{
		delete[] name;
		cout << "called destructor" << endl;
	}
};


int main()
{
	Person man1("Woo Seop Jung", 21);  //let's say man1.*name point's address '0xAA'
	Person man2("Elon Musk", 48);      //let's say man2.*name point's address '0xBB'
	Person man2 = man1;		//deep copy, the code is same as 'Person man2(man1);'
	man1.ShowPersonInfo();
	man2.ShowPersonInfo();	//error fixed

	return 0;
}

To avoid the leak of memory, '~Person()' once deallocate memory by delete in line32.

 

And in line19 'Person(const Person& copy)' overrides the default assignment operator.

 

It fixed the string problem by copying string from '0xAA' to '0xBB', not copying the address '0xAA' to pointer 'man2.*name'.

 

 

 

 

 

 

 

 

[참고자료]

- 윤성우의 열혈 C++ 프로그래밍