Is the destructor called if the constructor throws an exception?

前端 未结 8 972
不知归路
不知归路 2020-11-29 06:57

Looking for an answer for C# and C++. (in C#, replace \'destructor\' with \'finalizer\')

8条回答
  •  天命终不由人
    2020-11-29 07:50

    It does for C# (see code below) but not for C++.

    using System;
    
    class Test
    {
        Test()
        {
            throw new Exception();
        }
    
        ~Test()
        {
            Console.WriteLine("Finalized");
        }
    
        static void Main()
        {
            try
            {
                new Test();
            }
            catch {}
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
    }
    

    This prints "Finalized"

提交回复
热议问题