我是否需要在C++/CLI(VS 2010/.Net 4.0)中对IDisposable对象调用delete

pst*_*jds 3 c++-cli .net-4.0 visual-studio-2010

我的印象是,在C++/CLI方法中,如果我使用的类实现了IDisposable,则当对象超出范围时,会自动调用dispose.最近我遇到了一些看起来像这样的代码:

void SomeClass::SomeMethod()
{
    DisposableObject^ myObject = nullptr;
    try
    {
         // Some code that creates a DisposableObject and assigns to myObject
    }
    finally
    {
        if (myObject != nullptr)
        {
            // this is instead of IDisposable.Dispose
            delete myObject;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题确实有两个方面.首先,我是否需要显式调用delete该对象.其次,在纯C++中,它是安全地调用删除一个空物体上,并在C++/CLI是行为的改变,只是不知道,因为它好像我并不真的需要围绕删除通话nullptr检查,如果该行为是same在C++/CLI(我理解行为同样是一个相对术语,因为托管对象上的删除操作与非托管对象上的操作不同).

ild*_*arn 5

  1. 你永远不会严格要求在.NET中处理任何东西(除非这个类被错误地实现,例如在有保证的情况下缺少终结器),但你绝对应该尽可能地使用它.使用堆栈语义不需要在不需要delete延迟初始化时直接调用:

    void SomeClass::SomeMethod() {
        DisposableObject myObject;
        // ...
        // Some code that uses myObject
    } // myObject is disposed automatically upon going out of scope
    
    Run Code Online (Sandbox Code Playgroud)

    使用msclr::auto_handle<>与堆栈语义组合消除了对需要try..finally延迟初始化时需要:

    void SomeClass::SomeMethod() {
        msclr::auto_handle<DisposableObject> myObject;
        // ...
        // Some code that creates a DisposableObject and assigns to myObject
        // ...
        // Some code that uses myObject
    } // myObject is disposed automatically upon going out of scope
    
    Run Code Online (Sandbox Code Playgroud)
  2. 调用delete一个值nullptr是完全安全的,定义的行为,就像在C++中一样 - 不需要if.