从.NET构造函数抛出异常抛出、函数、异常、NET

2023-09-03 16:21:16 作者:对伱微笑╮纯属伱很可笑

有没有当我从类似下面的构造函数抛出一个异常任何内存泄漏?

Are there any memory leaks when I throw an exception from a constructor like the following?

class Victim
{
    public string var1 = "asldslkjdlsakjdlksajdlksadlksajdlj";

    public Victim()
    {
        //throw new Exception("oops!");
    }
}

将失败的对象被垃圾收集器收集的?

Will the failing objects be collected by the garbage collector?

推荐答案

在这一般从没有内存泄漏的角度来看安全。但是,如果你分配非托管资源的类型从构造函数抛出异常是危险的。看看下面的例子

In general this is safe from the perspective of not leaking memory. But throwing exceptions from a constructor is dangerous if you allocate unmanaged resources in the type. Take the following example

public class Foo : IDisposable { 
  private IntPtr m_ptr;
  public Foo() {
    m_ptr = Marshal.AllocHGlobal(42);
    throw new Exception();
  }
  // Most of Idisposable implementation ommitted for brevity
  public void Dispose() {
    Marshal.FreeHGlobal(m_ptr);
  }
}

本课程将每次你想,即使你使用一个使用块创建时出现内存泄漏。例如,该泄漏内存。

This class will leak memory every time you try to create even if you use a using block. For instance, this leaks memory.

using ( var f = new Foo() ) {
  // Won't execute and Foo.Dispose is not called
}
 
精彩推荐
图片推荐