Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 956
David Locke Avatar asked Oct 08 '08 20:10

David Locke


People also ask

What is difference between deep copy and shallow copy in Python?

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original. A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

What is a deep copy?

A deep copy of an object is a copy whose properties do not share the same references (point to the same underlying values) as those of the source object from which the copy was made.

What is shallow copy and deep copy in CPP?

1. When we create a copy of object by copying data of all member variables as it is, then it is called shallow copy. When we create an object by copying data of another object along with the values of memory resources that reside outside the object, then it is called a deep copy.


2 Answers

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

Shallow:

Before CopyShallow CopyingShallow 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 CopyDeep CopyingDeep 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.

like image 55
dlamblin Avatar answered Oct 07 '22 15:10

dlamblin


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.

like image 39
S.Lott Avatar answered Oct 07 '22 16:10

S.Lott