Net Deep Learning notes (4): Deep copy and shallow copy)

Source: Internet
Author: User

1. Basic concepts:

First, we should know what deep copy and shallow copy are ).

A. Shallow copy Shadow Clone: only copies the basic type of the object. The object type still belongs to the original reference.
B. Deep copy (deep copy): Copies the basic class of the object, and also copies the object in the original object. A new object is generated completely.

We know that C ++ has the concepts of copy constructor and copy assignment function. A shallow copy is a one-to-one value assignment between member data: assign values to the values to be copied. However, there may be a situation where the object also contains resources. The resource here can be a heap resource or a file. When the value is copied, the two objects use the same resources and can access the resources, which leads to problems. Deep copy is used to solve this problem. It also assigns resources once so that objects have different resources, but the content of resources is the same. For heap resources, a heap memory is being opened to copy the original content.

If the object you copied references an external content (such as the Data allocated to the stack), let the new and old objects point to the same external content when copying the object, it is a shallow copy. If an independent copy of an external object is created for the new object when the object is copied, It is a deep copy.
The concept in C # is similar to that in C ++. We can refer to previous concepts. The differences between deep copy and shallow copy can be seen from the definition. First, copying a field of the numeric type in the object to a new object, and copying a reference field of the object to the target object. If you change the value of the referenced field in the target object, it will be reflected in the original object, that is, the corresponding field in the original object will also change.

The difference between deep copy and shallow copy is the processing of reference copy. Deep copy creates and assigns values to fields of the corresponding value type in the original object in the new object. A new reference type will not be created for the shortest copy, and the same type reference will be returned. The deep copy operation creates a new object and returns the reference words of the new object. The observer mode in C # is an example of the shortest copy. We keep only copies of objects.

 

2. Implementation of deep copy and light copy:
From the above concepts, we have learned the differences between C # Deep copy and shallow copy. This determines that the two have different implementation methods.

For Value Type:
A. Shallow copy: this function is directly implemented by assigning values and other operations to copy the value type fields in the object to the new object.
B. Deep copy: this function is directly implemented by assigning values to the new object. The same as the shortest copy.

For reference types:
A. Shallow copy: The memberwiseclone method creates a shallow copy. The method is to create a new object. If the field is of the value type, perform a one-on-one copy of the field. If the field is of reference type, copy and reference the original object, and the original object references the same object.

B. Deep copy: copy the object application, and copy the actual content of the object. That is, a new object is created, which does not affect the content of the original object.
In this case, you need to implement the clone method provided in the icloneable interface.

The difference is that the mechanism is different when the implementation of the Reference type is deep copy and shallow copy. The former is the implementation of the memberwiseclone method, and the latter is the clone method provided in the icloneable interface through inheritance, implements deep copy of objects.

3. Code implementation and analysis:

Next let's take a look at the specific code implementation part. The first thing we will introduce is the value type.

A. Implementation of shallow copy of value type. The Code is as follows:
/// <Summary>
/// Array = assign value (direct copy), that is, transfer the reference, pointing to the same address:
/// </Summary>
Public void methodshallowcopydirectly ()
{
Int [] arrayint = {0, 1, 2, 3 };

// Change the value of any variable, and the other variable will be changed.
Int [] newarrayint = arrayint;
// Change the new array variable:
Newarrayint [0] = 8;
Console. writeline ("copying arrays (directly copying), change the first value of the new array to 8, original value {0}, new value {1}", arrayint [0], newarrayint [0]);
}
/// <Summary>
/// Arrayint. copyto, create a new array without affecting the original value
/// </Summary>
Public void methodshallowcopyarraycopyto ()
{
Int [] arrayint = {0, 1, 2, 3 };

// Copyto () method
Int [] newarrayint = new int [5]; // create a new array and copy it by value without affecting the original value
Arrayint. copyto (newarrayint, 0 );
Newarrayint [0] = 8;
Console. writeline ("array. copyto, change the first value of the new array to 8, original value {0}, new value {1}", arrayint [0], newarrayint [0]);

}
/// <Summary>
/// Array. Copy: Specifies the shortest copy of the value type. A new array is created and copied by value without affecting the original value.
/// </Summary>
Public void methodshallowcopyarraycopy ()
{
Int [] arrayint = {0, 1, 2, 3 };
// Copy () method
Int [] newarrayint = new int [4];
Array. Copy (arrayint, newarrayint, 0); // create a new array, copy by value, without affecting the original value
Newarrayint [0] = 8;
Console. writeline ("array. Copy, change the first value of the new array to 8, original value {0}, new value {1}", arrayint [0], newarrayint [0]);

}
/// <Summary>
/// Array. Clone (), shortest copy
/// </Summary>
Public void methodshallowcopyarrayclone ()
{
Int [] arrayint = {0, 1, 2, 3 };
// Array clone () method
Int [] newarrayint = arrayint. Clone () as int []; // copy by value without affecting the original value
Newarrayint [0] = 8;
Console. writeline ("array. clone (), change the first value of the new array to 8, original value {0}, new value {1} ", arrayint [0], newarrayint [0]);
}
/// <Summary>
///. Shortest copy: (reference type). The elements in the array are reference types, copying a reference of it. Changing the new copy will change the original object.
/// </Summary>
Public void methodshallowcopystringarraycopyto ()
{
String [] sarray = {"string0", "string1", "string2 "};
String [] snewarray = sarray;
// Copy a new object.
Sarray. copyto (snewarray, 0 );

// Change the value of the new object. The value of the source object will also be changed.
Snewarray [0] = "frankxulei ";
Console. writeline ("shortest copy of array: (reference type), change the first value to frankxulei, original value {0}, new value {1}", sarray [0], snewarray [0]);
}
/// <Summary>
//// Deep copy of the string array. To include a deep copy of an array of the reference type, you must iterate the array and create a new object.
/// </Summary>
Public void methoddeepcopystringarray ()
{
String [] sarray = new string [] {"string0", "string1", "string2", "string3 "};
String [] snewarray = new string [4]; // iteratively creates an object
For (INT I = 0; I <sarray. length; I ++)
{
String stemp = string. empty;
Stemp = sarray [I];
Snewarray [I] = stemp;
}
Snewarray [0] = "frankxulei ";
Console. writeline ("copying arrays (directly copying), change the first value of the new array to frankxulei, original value {0}, new value {1}", sarray [0], snewarray [0]);
}

The = value (directly copy) of the array, that is, the reference transfer, points to the same address, so changing the value of any of the variables will also be changed. Arrayint. copyto, creates a new array. Changing the new array variable does not affect the original value. Array. Copy: indicates a shortest copy of the value type. A new array is created and copied by value without affecting the original value. . Shallow copy: (reference type). The element in the array is the reference type. Copying is a reference of it. Changing the new copy will change the original object.

B. Deep copy Implementation of the reference type:

Defines the inherited interface icloneable for a vehicle class.

Public class cardeepclone: icloneable
{
// Name, reference type
Public String _ name = string. empty;
// Price, Value Type
Public int _ price = 0;
// Constructor
Public cardeepclone ()
{
}
// Overload Constructor
Public cardeepclone (string name, int price)
{
_ Name = Name;
_ Price = price;
}
// Deep copy. You need to regenerate the object to return the instance of the new object.
Public object clone ()
{

// Deep copy
Cardeepclone OBJ = new cardeepclone (); // recreate the cardeepclone object
// Obj. Member = (classa) member. Clone ();
Return OBJ;
}
}
C. Implementation of the shallow copy of the reference type:

The shortest method is this. memberwiseclone (); creates a shortest copy of the current object and returns the same object reference. The implementation code of deep copy is to recreate the cardeepclone object through cardeepclone OBJ = new cardeepclone. This is the difference between the two in implementation.

Public class carshallowclone: icloneable
{
// Name, reference type
Public String _ name = string. empty;
// Price, Value Type
Public int _ price = 0;
// Constructor
Public carshallowclone (string name, int price)
{
_ Name = Name;
_ Price = price;
}
// Shortest copy. The memberwiseclone method returns the shortest copy of the object.
Public object clone ()
{
Return this. memberwiseclone (); // creates a shortest copy of the current object and returns the same object reference.
}
}

D. Client test code implementation:

This includes the implementation test of the shortest of the value type and the deep copy of the string type array. And the object's deep copy and shortest. The Code is as follows:

Valuetypecopy _ shallowcopy = new valuetypecopy ();
Console. writeline ("Value Type shallow copy demo Value Type shallow copy .................. ");
_ Shallowcopy. methodshallowcopydirectly (); // values are directly assigned.
_ Shallowcopy. methodshallowcopyarrayclone (); // call the clone () method of the array, shallowcopy
_ Shallowcopy. methodshallowcopyarraycopy (); // arraycopy Method
_ Shallowcopy. methodshallowcopyarraycopyto (); // arraycopyto () method
_ Shallowcopy. methodshallowcopystringarraycopyto (); // arraycopyto () method
 
_ Shallowcopy. methoddeepcopystringarray (); // deep copy character array

 

// Deepcopy test deep copy, re-generate the object, the modification to the new object will not change the original object Value
Console. writeline ("Object deep copy demo object deep copy ..................... ");
Cardeepclone _ cardeepclone1 = new cardeepclone ("benz700", 700 );
// Deep copy
Console. writeline ("deepcopy test deep copy, original object name {0}", _ cardeepclone1. _ name );
Cardeepclone _ cardeepclone2 = _ cardeepclone1.clone () as cardeepclone;

Console. writeline ("deepcopy test deep copy, new object name {0}", _ cardeepclone2. _ name );
// Modify the name of the new object
_ Cardeepclone2. _ name = "benz800 ";
Console. writeline ("deepcopy test deep copy, new object name changed to {0}", _ cardeepclone2. _ name );
// Output Object Information
Console. writeline ("deepcopy test deep copy, original object name: {0}, New Object Name: {1}", _ cardeepclone1. _ name, _ cardeepclone2. _ name );

// Shallowcopy test. The modification of the new object will change the value of the original object.
Console. writeline ("Object shallow copy demo object shallow copy ..................... ");
Carshallowclone _ carshallowclone1 = new carshallowclone ("bmw3", 300 );
Console. writeline ("shallowcopy test light copy, original object name {0}", _ carshallowclone1. _ name );
// A shortest object
Carshallowclone _ carshallowclone2 = _ carshallowclone1.clone () as carshallowclone;
Console. writeline ("shallowcopy test light copy, new object name {0}", _ carshallowclone2. _ name );
// Modify the New Object Name
_ Carshallowclone2. _ name = "bmw7 ";
Console. writeline ("shallowcopy test light copy, new object name changed to {0}", _ carshallowclone2. _ name );
// Output Object Information
Console. writeline ("shallowcopy test light copy, original object name {0}, new object name {1}", _ carshallowclone1. _ name, _ carshallowclone2. _ name );

First, test the different shallowcopy methods of the value type, and instantiate the class valuetypecopy _ shallowcopy = new valuetypecopy ();
Perform a copy test on the value type. Including: _ shallowcopy. methodshallowcopydirectly (); direct value assignment copy,
_ Shallowcopy. methodshallowcopyarrayclone (); the clone () method of the array is called and the shallowcopy () method is used.
_ Shallowcopy. methodshallowcopyarraycopy (); arraycopy Method
_ Shallowcopy. methodshallowcopyarraycopyto (); arraycopyto () method
_ Shallowcopy. methodshallowcopystringarraycopyto (); arraycopyto () method
_ Shallowcopy. methoddeepcopystringarray (); the Code behind the deep copy character array is mainly used to test the differences between the two objects.

The running result is as follows:

4. Summary

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.