Search code examples
.netc++-cliidisposableusingfinally

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.


Solution

  • 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);
        // ...
    }