有没有当我从类似下面的构造函数抛出一个异常任何内存泄漏?
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
}
上一篇:我怎样才能纠正错误和QUOT;从一个线程比它在"?创建线程的其他访问线程、它在、错误、QUOT
下一篇:为什么DateTime.Now.ToString(" U")无法正常工作?无法正常、工作、Now、DateTime