Trusted answers to developer questions

Deep copying vs. shallow copying

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

Let’s take two objects of the same type (A and B) where the contents of A are to be copied into B. Let’s see how this copying will take place in the case of ​deep and shallow copying.

Shallow copying

In this case, a copy of the references/addresses to A are c​opied into B. Hence, the addresses of A and B will be the same as they will be pointing to the same memory location.

svg viewer

When either of the two object pointers is deleted, the other object loses the referenced object too. This is because the other object is still pointing to the memory allocation that has already been freed. Now, the other non-deleted object pointer is a dangling pointer.

When dealing with a ​large number of pointers during programming, shallow copying​ is a bad idea since deleting one of the referenced objects, even accidentally, means that there are now a lot of dangling pointers in the code.

Deep copy

In the case of deep copying, a copy of all the members of A are made, memory is allocated in a different location for B, and the copied members are assigned to B. The more accurate term to use would be “cloning” since they are identical yet different (i.e.,​ stored as two different entities in the memory space).

svg viewer

Now, in the case of deep copying, if one object pointer is deleted, the other will still have​ access to the referenced object’s value because it is still valid in the memory.

Deep copying consumes much more memory, ​but it makes your code more robust. It also eliminates the risk of dangling pointers in the code since each object pointer points to a different location in the memory.

RELATED TAGS

deep
shallow
copying
vs
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?