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

问题描述 投票:6回答:1

我知道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; }
}

但这似乎不太好。

.net c++-cli idisposable using finally
1个回答
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);
    // ...
}
© www.soinside.com 2019 - 2024. All rights reserved.