开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜