简体   繁体   English

析构函数未正确调用

[英]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# . 哪里应该为r1,r2,r3,r4调用4次。我是否缺少某些东西。请帮助我,我是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. 因此〜Class()仅被调用两次-每个对象一次。

Some analogous C++ code is: 一些类似的C ++代码是:

    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. 这只会调用Class1析构函数两次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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