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

David Locke picture David Locke · Oct 8, 2008 · Viewed 632.8k times · Source

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

Answer

dlamblin picture dlamblin · Oct 8, 2008

Breadth vs Depth; think in terms of a tree of references with your object as the root node.

Shallow:

Before Copy Shallow Copying Shallow Done

The variables A and B refer to different areas of memory, when B is assigned to A the two variables refer to the same area of memory. Later modifications to the contents of either are instantly reflected in the contents of other, as they share contents.

Deep:

Before Copy Deep Copying Deep Done

The variables A and B refer to different areas of memory, when B is assigned to A the values in the memory area which A points to are copied into the memory area to which B points. Later modifications to the contents of either remain unique to A or B; the contents are not shared.