C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Execute statement when leaving scope

From: Tom Honermann <tom_at_[hidden]>
Date: Mon, 12 Dec 2022 13:10:39 -0500
You might be interested in the defer proposal for C. See N2895: A simple
defer feature for C
<https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2895.htm>.

Tom.

On 12/12/22 4:33 AM, Frederick Virchanza Gotham via Std-Proposals wrote:
> 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 18:10:41