C++ Logo

std-proposals

Advanced search

[std-proposals] Execute statement when leaving scope

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Mon, 12 Dec 2022 09:33:39 +0000
Sometimes we want to make sure that a statement is executed when a
scope is exited (whatever way it is exited -- be it by a return
statement, or by the throwing of an exception, whichever way).

We can achieve this as follows:

void Func(void)
{
    Handle h = GetResource("monkey");

    if ( ! h ) return;

    struct MakeSureReleased {
        Handle const h;
        MakeSureReleased(Handle const arg) : h(arg) {}
        ~MakeSureReleased(void) { FreeResource(h); }
    };

    MakeSureReleased my_releaser(h);

    // The rest of the function goes here
}

A few popular libraries, such as Boost, have shorthand for doing this:

void Func(void)
{
    Handle h = GetResource("monkey");

    if ( ! h ) return;

    BOOST_SCOPE_EXIT()
    {
        FreeResource(h);
    } BOOST_SCOPE_EXIT_END

    // The rest of the function goes here
}

I propose that we should be able to achieve this in C++26 with some
simple syntax as follows:

void Func(void)
{
    Handle h = GetResource("monkey");

    if ( ! h ) return;

    ~ { FreeResource(h); }

    // The rest of the function goes here
}

I also propose that this new expression would be very versatile and
that you could use it in conditional code branching as follows:

void Func(void)
{
    Handle h = GetResource("monkey");

    if ( ! h ) return;

    if ( IsHardwareDevice(h) ) ~ { FreeDevice(h); }
    else ~ { FreeResource(h) };

    // The rest of the function goes here
}

Received on 2022-12-12 09:33:51