What is the difference between a deep copy and a shallow copy?
|
|
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. |
|||||||||||||||||||||
|
|
Breadth vs Depth; think in terms of a tree of references with your object as the root node. Shallow:
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:
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. |
|||||||||||||||||||||
|
|
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. This wiki article has a great diagram. |
||||
|
|
|
Especially For iOS Developers: If B and A point to the same memory location If B and A point to different memory locations B memory address is same as A's B has same contents as A's |
|||||||||
|
|
Shallow copy: Copies the member values from one object into another. Deep Copy: Copies the member values from one object into another. Example:
|
||||
|
|
|
Try to consider following image For example Object.MemberwiseClone creates a shallow copy link and using ICloneable interface you can get deep copy as described here |
|||||||||||||
|
|
I haven't seen a short, easy to understand answer here--so I'll give it a try. With a shallow copy, any object pointed to by the source is also pointed to by the destination (so that no referenced objects are copied). With a deep copy, any object pointed to by the source is copied and the copy is pointed to by the destination (so there will now be 2 of each referenced object). This recurses down the object tree. |
||||
|
|
|
{Imagine two objects: A and B of same type _t(with respect to C++) and you are thinking about shallow/deep copying A to B} Shallow Copy: Simply makes a copy of the reference to A into B. Think about it as a copy of A's Address. So, the addresses of A and B will be the same i.e. they will be pointing to the same memory location i.e. data contents. Deep copy: Simply makes a copy of all the members of A, allocates memory in a different location for B and then assigns the copied members to B to achieve deep copy. In this way, if A becomes non-existant B is still valid in the memory. The correct term to use would be cloning, where you know that they both are totally the same, but yet different (i.e. stored as two different entities in the memory space). You can also provide your clone wrapper where you can decide via inclusion/exclusion list which properties to select during deep copy. This is quite a common practice when you create APIs. You can choose to do a Shallow Copy ONLY_IF you understand the stakes involved. When you have enormous number of pointers to deal with in C++ or C, doing a shallow copy of an object is REALLY a bad idea. EXAMPLE_OF_DEEP COPY_ An example is, when you are trying to do image processing and object recognition you need to mask "Irrelevant and Repetitive Motion" out of your processing areas. If you are using image pointers, then you might have the specification to save those mask images. NOW... if you do a shallow copy of the image, when the pointer references are KILLED from the stack, you lost the reference and its copy i.e. there will be a runtime error of access violation at some point. In this case, what you need is a deep copy of your image by CLONING it. In this way you can retrieve the masks in case you need them in the future. EXAMPLE_OF_SHALLOW_COPY I am not extremely knowledgeable compared to the users in StackOverflow so feel free to delete this part and put a good example if you can clarify. But I really think it is not a good idea to do shallow copy if you know that your program is gonna run for an infinite period of time i.e. continuous "push-pop" operation over the stack with function calls. If you are demonstrating something to an amateur or novice person (e.g. C/C++ tutorial stuff) then it is probably okay. But if you are running an application such as surveillance and detection system, or Sonar Tracking System, you are not supposed to keep shallow copying your objects around because it will kill your program sooner or later. |
||||
|
|
'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. |
|||
|
|
|
Just for the sake of easy understanding you could follow this article: https://www.cs.utexas.edu/~scottm/cs307/handouts/deepCopying.htm Shallow Copy: Deep 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, only the reference addresses are copied i.e., only the memory address is copied. In this figure, the Now if this is shallow copy, lets see what's deep copy? 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.
In this figure, the MainObject1 have fields |
|||||
|
|
In object oriented programming, a type includes a collection of member fields. These fields may be stored either by value or by reference (i.e., a pointer to a value). In a shallow copy, a new instance of the type is created and the values are copied into the new instance. The reference pointers are also copied just like the values. Therefore, the references are pointing to the original objects. Any changes to the members that are stored by reference appear in both the original and the copy, since no copy was made of the referenced object. In a deep copy, the fields that are stored by value are copied as before, but the pointers to objects stored by reference are not copied. Instead, a deep copy is made of the referenced object, and a pointer to the new object is stored. Any changes that are made to those referenced objects will not affect other copies of the object. |
|||
|
|
|
'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. |
|||||
|
|
|||||||||
|
|
|||
|
|
|
In Simple Terms, a Shallow Copy is similar to Call By Reference and a Deep Copy is similar to Call By Value In Call By Reference, Both formal and actual parameters of a function refers to same memory location and the value. In Call By Value, Both formal and actual parameters of a functions refers to different memory location but having the same value. |
|||
|
|
|
Shallow Copy- Reference variable inside original and shallow-copied objects have reference to common object. Deep Copy- Reference variable inside original and deep-copied objects have reference to different object.
main class is following-
OutPut of above will be-
Any change made in origional object will reflect in shallow object not in deep object.
OutPut- ViSuaLBaSiC C |
||||
|
|
|
Imagine there are two arrays called arr1 and arr2.
|
|||
|
|
|
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. 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. |
|||
|
|
|
Taken from [blog]: http://sickprogrammersarea.blogspot.in/2014/03/technical-interview-questions-on-c_6.html Deep copy involves using the contents of one object to create another instance of the same class. In a deep copy, the two objects may contain ht same information but the target object will have its own buffers and resources. the destruction of either object will not affect the remaining object. The overloaded assignment operator would create a deep copy of objects. Shallow copy involves copying the contents of one object into another instance of the same class thus creating a mirror image. Owing to straight copying of references and pointers, the two objects will share the same externally contained contents of the other object to be unpredictable. Explanation: Using a copy constructor we simply copy the data values member by member. This method of copying is called shallow copy. If the object is a simple class, comprised of built in types and no pointers this would be acceptable. This function would use the values and the objects and its behavior would not be altered with a shallow copy, only the addresses of pointers that are members are copied and not the value the address is pointing to. The data values of the object would then be inadvertently altered by the function. When the function goes out of scope, the copy of the object with all its data is popped off the stack. If the object has any pointers a deep copy needs to be executed. With the deep copy of an object, memory is allocated for the object in free store and the elements pointed to are copied. A deep copy is used for objects that are returned from a function. |
|||
|
|
|
To add more to other answers,
|
|||
|
|
|
Copying ararys : Array is a class, which means it is reference type so array1 = array2 results in two variables that reference the same array. But look at this example:
shallow clone means that only the memory represented by the cloned array is copied. If the array contains value type objects, the values are copied; if the array contains reference type, only the references are copied - so as a result there are two arrays whose members reference the same objects. To create a deep copy—where reference type are duplicated, you must loop through the array and clone each element manually. |
|||||||||||||
|
|
Shallow copying is creating a new object and then copying the non-static fields of the current object to the new object. If a field is a value type --> a bit-by-bit copy of the field is performed; for a reference type --> the reference is copied but the referred object is not; therefore the original object and its clone refer to the same object. Deep copy is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type --> a bit-by-bit copy of the field is performed. If a field is a reference type --> a new copy of the referred object is performed. The classes to be cloned must be flagged as [Serializable]. |
|||||
|
|
In shallow cloning, only primitive properties of an object are cloned but its reference type is not cloned. In deep cloning, both primitive types and also reference types of an object are cloned. |
|||
|
|
|
Adding to all the above definitions, one more and most commonly used deep copy, is in the copy constructor (or overloading assignment oprator) of the class. Shallow copy --> is when you are not providing copy constructor. Here, only the object gets copied but not all the members of the class are copied. Deep copy --> is when you have decided to implement copy constructor or overload assignment in your class and allows copying all the members of the class.
|
|||
|
|
|
The copy constructor is used to initialize the new object with the previously created object of the same class. By default compiler wrote a shallow copy. Shallow copy works fine when dynamic memory allocation is not involved because when dynamic memory allocation is involved then both objects will points towards the same memory location in a heap, Therefore to remove this problem we wrote deep copy so both objects have their own copy of attributes in a memory. In order to read the details with complete examples and explanations you could see the article C++ constructors. |
||||
|
|
|
To add just a little more for confusion between shallow copy and simply assign a new variable name to list. "Say we have:
This statement creates 3 lists: 2 inner lists and one outer list. A reference to the outer list is then made available under the name x. If we do
no data gets copied. We still have the same 3 lists in memory somewhere. All this did is make the outer list available under the name y, in addition to its previous name x. If we do
or
This creates a new list with the same contents as x. List x contained a reference to the 2 inner lists, so the new list will also contain a reference to those same 2 inner lists. Only one list is copied—the outer list. Now there are 4 lists in memory, the two inner lists, the outer list, and the copy of the outer list. The original outer list is available under the name x, and the new outer list is made available under the name y. The inner lists have not been copied! You can access and edit the inner lists from either x or y at this point! If you have a two dimensional (or higher) list, or any kind of nested data structure, and you want to make a full copy of everything, then you want to use the deepcopy() function in the copy module. Your solution also works for 2-D lists, as iterates over the items in the outer list and makes a copy of each of them, then builds a new outer list for all the inner copies." |
|||
|
|
|
shallow copy will not create new reference but deep copy will create the new reference. Here is the program to explain the deep and shallow copy
} |
|||
|
|
protected by Community♦ Nov 6 '14 at 8:59
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?




