Deep copy VS shallow copy

What is the difference between deep copy and shallow copy? Explain how you would use each.

A shallow copy copies all the member values from one object to another. A deep copy does all this and also deep copies any pointer objects.

An example of shallow and deep copy is below.

C++:
01 struct Test{
02   char* ptr;
03 };
04 
05 void shallow_copy(Test& src, Test& dest){
06   dest.ptr=src.ptr;
07 }
08 
09 void deep_copy(Test& src, Test& dest){
10   dest.ptr=malloc(strlen(src.ptr)+1);
11   memcpy(dest.ptr,src.ptr);
12 }
Note that shallow_copy may cause a lot of programming run time errors, especially with the creation and deletion of objects. Shallow copy should be used very carefully and only when a programmer really understands what he wants to do. In most cases, shallow copy is used when there is a need to pass information about a complex structure without actual duplication of data. One must also be careful with destruction of objects in a shallow copy.
In real life, shallow copy is rarely used. Deep copy should be used in most cases, especially when the size of the copied structure is small.
Advertisements
This entry was posted in C++. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s