Deep Copy And Shallow Copy

What is Shallow Copy?

Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the reference addresses are copied i.e., only the memory address is copied.

shallow_copy
In this figure, the MainObject1 have fields “field1” of int type, and “ContainObject1” of ContainObject type. When you do a shallow copy of MainObject1, MainObject2 is created with “field2” containing the copied value of “field1” and still pointing to ContainObject1 itself. Observe here and you will find that since field1 is of primitive type, the values of it are copied to field2 but ContainedObject1 is an object, so MainObject2 is still pointing to ContainObject1. So any changes made to ContainObject1 in MainObject1 will reflect in MainObject2.

What is Deep Copy?

A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers.

deep_copy

In this figure, the MainObject1 have fields “field1” of int type, and “ContainObject1” of ContainObject type. When you do a deep copy of MainObject1, MainObject2 is created with “field2” containing the copied value of “field1” and “ContainObject2” containing the copied value of ContainObject1.So any changes made to ContainObject1 in MainObject1 will not reflect in MainObject2.

When to do shallow copy and deep copy?

Its very simple that if the object has only primitive fields, then obviously you will go for shallow copy but if the object has references to other objects, then based on the requiement, shallow copy or deep copy should be chosen. What I mean here is, if the references are not modified anytime, then there is no point in going for deep copy. You can just opt shallow copy. But if the references are modified often, then you need to go for deep copy. Again there is no hard and fast rule, it all depends on the requirement.

For code follow this example.


Leave a Reply

Your email address will not be published.