. NET heap and stack 03, reference type object copy and memory allocation,. net03

Source: Internet
Author: User

. NET heap and stack 03, reference type object copy and memory allocation,. net03

In ". NET heap and stack 01, basic concepts, value-type memory allocation", I learned the basic concepts of "Heap" and "stack", and value-type memory allocation. We know that when a method is executed, the value type instance allocates memory on the stack, and the reference type instance allocates memory on the heap. When the method execution is complete, instances on the "stack" are automatically released by the operating system, and instances on the "stack" are automatically released.. NET Framework.


In ". NET heap and stack 02, value type and reference type parameter transfer and memory allocation ", we understand the value type parameter and reference type parameter memory allocation during transfer.


This article focuses on copying referenced objects and allocating memory.

 

It mainly includes:
■ Copy members of reference type objects are all value types.
■ Copying a reference type object contains a reference type member

 

All copying members of reference type objects are value types.

public struct Shoe{               public string Color;           }            public class Dude           {                public string Name;                public Shoe RightShoe;                public Shoe LeftShoe;                 public Dude CopyDude()                {                     Dude newPerson = new Dude();                     newPerson.Name = Name;                     newPerson.LeftShoe = LeftShoe;                     newPerson.RightShoe = RightShoe;                      return newPerson;                }                 public override string ToString()                {                     return (Name + " : Dude!, I have a " + RightShoe.Color  +                         " shoe on my right foot, and a " +                          LeftShoe.Color + " on my left foot.");                }            }           public static void Main()           {                  Dude Bill = new Dude();                  Bill.Name = "Bill";                  Bill.LeftShoe = new Shoe();                  Bill.RightShoe = new Shoe();                  Bill.LeftShoe.Color = Bill.RightShoe.Color = "Blue";                   Dude Ted =  Bill.CopyDude();                  Ted.Name = "Ted";                  Ted.LeftShoe.Color = Ted.RightShoe.Color = "Red";                   Console.WriteLine(Bill.ToString());                  Console.WriteLine(Ted.ToString());                       }

 

Output result:
Bill: Dude !, I have a Red shoe on my right foot, and a Red on my left foot
Ted: Dude !, I have a Red shoe on my right foot, and a Red on my left foot

 

In the preceding example, when the attributes and members of the reference type are all value types, the copy operation completely copies the data.

 

Reference Type object copy contains reference type members

Change Shoe from struct value type to reference type class.

public class Shoe{               public string Color;           }

 

Run again and output the result:
Bill: Dude !, I have a Red shoe on my right foot, and a Red on my left foot
Ted: Dude !, I have a Red shoe on my right foot, and a Red on my left foot

 

When the Dude class contains the Shoe attribute of the reference type, the situation on the managed stack is as follows:

 

After copying, the Shoe type attributes of the two Dude direct to the Shoe instance in the same managed heap. Changing the Shoe value will affect both Dude.


Obviously, this is not the expected full copy. What if it is done completely?
-- Implement the ICloneable Interface

 

The Clone () method of the ICloneable interface allows us to perform some custom settings during copying.

 

Let the reference class Shoe implement the ICloneable interface.

public class Shoe : ICloneable             {                  public string Color;                   public object Clone()                  {                      Shoe newShoe = new Shoe();                      newShoe.Color = Color.Clone() as string;                      return newShoe;                  }             }

In the preceding section, the Color attribute of Shoe's string type can be used. the Clone () method is used because string also implements the ICloneable interface. Because Clone () returns an object of the type, Color is used. after the Clone () method, you need to convert the object to the string type.


Now, in the CopyDude () method of the Dude class, when copying the Shoe type attribute, you can use the unique copy method Clone () of Shoe ().

public Dude CopyDude()                {                    Dude newPerson = new Dude();                     newPerson.Name = Name;                     newPerson.LeftShoe = LeftShoe.Clone() as Shoe;                     newPerson.RightShoe = RightShoe.Clone() as Shoe;                      return newPerson;                }

 

Client program.

public static void Main()           {                  Dude Bill = new Dude();                  Bill.Name = "Bill";                  Bill.LeftShoe = new Shoe();                  Bill.RightShoe = new Shoe();                  Bill.LeftShoe.Color = Bill.RightShoe.Color = "Blue";                   Dude Ted =  Bill.CopyDude();                  Ted.Name = "Ted";                  Ted.LeftShoe.Color = Ted.RightShoe.Color = "Red";                   Console.WriteLine(Bill.ToString());                  Console.WriteLine(Ted.ToString());                        }

 

Output result:
Bill: Dude !, I have a Blue shoe on my right foot, and a Blue on my left foot
Ted: Dude !, I have a Red shoe on my right foot, and a Red on my left foot

This is what we expect to be a full copy!

 

Full copy: the hosting stack is like this:

 

Of course, you can also include both the value type and reference type members, and copy the class to implement the ICloneable interface.

public class Dude: ICloneable           {                public string Name;                public Shoe RightShoe;                public Shoe LeftShoe;                 public override string ToString()                {                     return (Name + " : Dude!, I have a " + RightShoe.Color  +                         " shoe on my right foot, and a " +                          LeftShoe.Color + " on my left foot.");                    }                  #region ICloneable Members                   public object Clone()                  {                       Dude newPerson = new Dude();                       newPerson.Name = Name.Clone() as string;                       newPerson.LeftShoe = LeftShoe.Clone() as Shoe;                       newPerson.RightShoe = RightShoe.Clone() as Shoe;                        return newPerson;                  }                   #endregion             }

 

Client call.

public static void Main()           {               Class1 pgm = new Class1();                   Dude Bill = new Dude();                  Bill.Name = "Bill";                  Bill.LeftShoe = new Shoe();                  Bill.RightShoe = new Shoe();                  Bill.LeftShoe.Color = Bill.RightShoe.Color = "Blue";                   Dude Ted =  Bill.Clone() as Dude;                  Ted.Name = "Ted";                  Ted.LeftShoe.Color = Ted.RightShoe.Color = "Red";                   Console.WriteLine(Bill.ToString());                  Console.WriteLine(Ted.ToString());                        }

 

Output result:
Bill: Dude !, I have a Blue shoe on my right foot, and a Blue on my left foot.
Ted: Dude !, I have a Red shoe on my right foot, and a Red on my left foot.

 

This is also the expected full copy!

 

References:
C # Heap (ing) Vs Stack (ing) in. NET: Part III

 

". NET heap and stack" series include:

. NET heap and stack 01, basic concepts, value type memory allocation. NET heap and stack 02, value type and reference type parameter transfer and memory allocation. NET heap and stack 03, reference type object copy and Memory Allocation
Heap and stack problems in c #

Your understanding is accurate.

In fact, the reference variable p is placed on the stack of the current thread, which occupies 4 bytes (32-bit OS) and points to the object on the managed stack.

In addition, to ensure the continuity of the managed heap memory and the performance of memory allocation ,. net's garbage collection mechanism will regularly scan the managed heap, clear objects that no longer point to referenced variables, and move those objects that are still in use (also modify the reference variable p value, point it to a new address)-just like our disk fragment, this ensures the continuity of the hosted heap hollow memory and makes the allocation and access of the managed heap memory faster.

That's why Pointer Points cannot be directly directed to hosted objects in. Net. When the spam collector moves a hosted object, the pointer value cannot be updated at the same time, leading to the pointer pointing to the wrong address.

So ,. net also provides the keyword fixed to lock the hosted object and tell the Garbage Collector not to move the locked object. In this case, you can directly use the pointer. Of course, this is in unsafe mode)

Java defines a variable of the reference type to be connected only when the stack and heap memory are allocated.

1. For example, if only Object obj is written, the heap is not involved and the memory will only be allocated in the stack;
2. When an Object is new, such as new Object ();, the Object will be stored in the heap;
3. If it is written as Object obj = new Object (), the first address of the Object in the heap is assigned to the obj variable. You can use obj to call the Object method, actually, the call is the method of the object pointed to by obj.

Related Article

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.