Deep copy and shallow copy in C++

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

My initial thoughts:
Deep copy is going to copy everything from an object to create a whole new object that is equal to the original object. Shallow copy, on the other hand, only copies the address of the object. That is, you create another reference to the original object. When you want to do some operations on the object but you don’t want to change it, you use deep copy. Otherwise, you use shallow copy.

Solution:

struct Test {
	char * ptr;
};

void shallow_copy(Test & src, Test & dest) {
	dest.ptr = src.ptr;
}

void deep_copy(Test & src, Test & dest) {
	dest.ptr = malloc(strlen(src.ptr) + 1)
	memcpy(dest.ptr, src.ptr);
}

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 (e.g., call by reference). One must also be careful with destruction of shallow copy.
In real life, shallow copy is rarely used. There is an important programming concept called “smart pointer” that, in some sense, is an enhancement of the shallow copy concept.
Deep copy should be used in most cases, especially when the size of the copied structure is small.

Advertisements

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

%d bloggers like this: