开发者

C++/CLI stack semantics equivalent of C#'s existing-object using statement?

开发者 https://www.devze.com 2023-02-22 22:32 出处:网络
I know that the C++/CLI equivalent to this C# code: using (SomeClass x = new SomeClass(foo)) { // ... } is this:

I know that the C++/CLI equivalent to this C# code:

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

is this:

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

But is there a similarly succinct and RAII-like way to express this:

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

Or:

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

? The closest working example I have is this:

SomeClass^ x = SomeFunctionThatReturnsThat(foo);
try
{
    // ...
}
fin开发者_如何学Cally
{
    if (x != nullptr) { delete x; }
}

But that doesn't seem as nice.


msclr::auto_handle<> is a smart pointer for managed types:

#include <msclr/auto_handle.h>

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

// or

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

精彩评论

暂无评论...
验证码 换一张
取 消