Alex Rivera | Logout

What is the difference between a deep copy and a shallow copy?

Asked 2008-10-08T20:22:42.850
753

What is the difference between a deep copy and a shallow copy?

Edit
Report

4 Answers

911

Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements.

Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated.

answered 2008-10-08T20:29:36.737
184

In short, it depends on what points to what. In a shallow copy, object B points to object A's location in memory. In deep copy, all things in object A's memory location get copied to object B's memory location.

The Wikipedia article Object copy has a great diagram.

answered 2008-10-08T20:24:11.427
37
char * Source = "Hello, world.";

char * ShallowCopy = Source;    

char * DeepCopy = new char(strlen(Source)+1);
strcpy(DeepCopy,Source);        

'ShallowCopy' points to the same location in memory as 'Source' does. 'DeepCopy' points to a different location in memory, but the contents are the same.

answered 2008-10-08T20:32:49.210
13

'ShallowCopy' points to the same location in memory as 'Source' does. 'DeepCopy' points to a different location in memory, but the contents are the same.

answered 2011-02-21T13:44:43.870

Your Answer