Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
{
    // ...
}
finally
{
    if (x != nullptr) { delete x; }
}

But that doesn't seem as nice.

like image 889
Miral Avatar asked Apr 06 '11 06:04

Miral


1 Answers

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);
    // ...
}
like image 90
ildjarn Avatar answered Sep 19 '22 03:09

ildjarn