简体   繁体   中英

Destructor is not getting called properly

I have been through the below code but while i am debugging the code i found like the destructor is being called for twice . Where as it should get called 4 times for r1,r2,r3,r4 .Am i missing something .Please help me , i am new to c# . Here at what time the structure object get destroyed .

using System;
struct Struct1
{
    public int Value;

}
class Class1
{
    public int Value = 0;
    ~Class1()
    {
        Console.WriteLine("Calling destructor");
    }
}
class Test
{
    static void Main()
    {
        Struct1 v1 = new Struct1();
        Struct1 v2 = v1;
        v2.Value = 123;
        Class1 r1 = new Class1();
        Class1 r2 = r1;
        r2.Value = 123;
        Console.WriteLine("Values: {0}, {1}", v1.Value, v2.Value);
        Console.WriteLine("Refs: {0}, {1}", r1.Value, r2.Value);
        vivek();
        viku();
        Console.ReadKey();
    }
    static void viku()
    {
        Struct1 v1 = new Struct1();
        Struct1 v2 = v1;
        v2.Value = 123;
        Console.WriteLine("Values: {0}, {1}", v1.Value, v2.Value);
    }

    static void vivek()
    {
        Class1 r3 = new Class1();
        Class1 r4 = r3;
        r4.Value = 15;
       // Console.WriteLine("Values: {0}, {1}", v1.Value, v2.Value);
        Console.WriteLine("Refs: {0}, {1}", r3.Value, r4.Value);
        Console.Write("Calling vivek");
    }

} 

Class1仅实例化两次,因此终结器当然只会执行两次。

    Class1 r1 = new Class1();
    Class1 r2 = r1;

and

    Class1 r3 = new Class1();
    Class1 r4 = r3;

Creates two separate objects each with two references. Even though you have four references there are still only two objects to finalize. So ~Class() is only invoked twice - once for each object.

Some analogous C++ code is:

    shared_ptr<Class1> r1(new Class1());
    shared_ptr<Class1> r2 = r1;

and

    shared_ptr<Class1> r3(new Class1());
    shared_ptr<Class1> r4 = r3;

This will only call the Class1 destructor twice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM