Wednesday, 8 December 2010

Difference between Deep copy and Shallow copy in C++

So what is the difference between 'Deep copy' (sometimes referred to as 'Hard copy') and 'Shallow copy' in C++

Shallow copy: Copies the member values from one object into another.

Deep Copy: Copies the member values from one object into another. Any pointer objects are duplicated and Deep Copied.

There are some interesting discussions on Stack Overflow here and here. A related discussions here is interesting as well.

Program to demonstrate as follows:


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>
#include<string>

using namespace
std;

class
MyString
{

public
:
MyString(){}
MyString(string str)
{

size = str.size();
data = new char(size+1); //+1 for '\0'
memcpy(data, str.c_str(), size+1);
}

//MyString(const MyString& copy); - Use default for Shallow
void DeepCopy(const MyString& copy) //Deep Copy
{
size = copy.size;
data = new char(size+1); //+1 for '\0'
memcpy(data, copy.data, size+1);
}

int
size;
char
* data;
};


int
main()
{

MyString m1("Zahid");
cout<<"\nm1.size = "<<m1.size<<", &m1.data = "<<(void *)m1.data<<", *m1.data = "<<m1.data<<endl;

MyString m2(m1); //Uses the default copy constructor - Shallow Copy
cout<<"\nm2.size = "<<m2.size<<", &m2.data = "<<(void *)m2.data<<", *m2.data = "<<m2.data<<endl;

MyString m3; //Another default constructor
m3.DeepCopy(m1);
cout<<"\nm3.size = "<<m3.size<<", &m3.data = "<<(void *)m3.data<<", *m3.data = "<<m3.data<<endl;

return
0;
}


Output as follows:


No comments:

Post a Comment