What is the difference between a deep copy and a shallow copy?
相关问题
- Name for a method that has only side effects
- Can a memory page be moved by modifying the page t
- copy one row from a table to another and insert va
- Best way to keep the user-interface up-to-date?
- Deep copy entity with NHibernate
相关文章
- Should client-server code be written in one “proje
- Algorithm for maximizing coverage of rectangular a
- Is there an existing solution for these particular
- Alternative of strcpy in c++
- What is Scope Creep? [closed]
- How do you perform a deep copy of a struct in Go?
- using Visual Studio to copy files?
- scala copy objects
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.
'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.
To add more to other answers,
I would like to give example rather than the formal definition.
This code shows a shallow copy:
This code shows a deep copy:
Imagine there are two arrays called arr1 and arr2.
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].