C ++ / CLI堆栈语义相当于C#的现有对象使用语句?

时间:2011-04-06 06:07:00

标签: .net c++-cli idisposable using finally

我知道C ++ / CLI等同于这个C#代码:

using (SomeClass x = new SomeClass(foo))
{
    // ...
}

就是这样:

{
    SomeClass x(foo);
    // ...
}

但是,有类似的简洁和类似RAII的方式来表达这一点:

using (SomeClass x = SomeFunctionThatReturnsThat(foo))
{
    // ...
}

或者:

SomeClass x = SomeFunctionThatReturnsThat(foo);
using (x)
{
    // ...
}

?我最接近的工作示例是:

SomeClass^ x = SomeFunctionThatReturnsThat(foo);
try
{
    // ...
}
finally
{
    if (x != nullptr) { delete x; }
}

但这似乎不太好。

1 个答案:

答案 0 :(得分:10)

msclr::auto_handle<>是托管类型的智能指针:

#include <msclr/auto_handle.h>

{
    msclr::auto_handle<SomeClass> x(SomeFunctionThatReturnsThat(foo));
    // ...
}

// or

SomeClass^ x = SomeFunctionThatReturnsThat(foo);
{
    msclr::auto_handle<SomeClass> y(x);
    // ...
}