C++ Logo


Advanced search

Re: [std-proposals] Dummy names for dummy objects

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Sun, 11 Jun 2023 16:57:12 +0100
On Sat, Jun 10, 2023 at 3:39 PM Arthur O'Dwyer via Std-Proposals
<std-proposals_at_[hidden]> wrote:
> See "The Auto() macro" for a way to do this without dummy names and with less visual noise.
> https://quuxplusone.github.io/blog/2018/08/11/the-auto-macro/

Here's how I do it:

template<typename Lambda>
struct OnScopeExit {
    bool active;
    Lambda f;
    explicit OnScopeExit(Lambda arg) : active(true), f(arg) {}
    ~OnScopeExit(void) { if ( active ) f(); }

And I put that inside a file called "auto_include.h".

Then I compile all my files with "g++ file.cpp -include auto_include.h".

Note that I have a boolean to make it inactive, for example:

    OnScopeExit scoper( [](){ ::close(fd); } );

    // Do something that might throw

    // Do something else that might throw

    // Do a third thing that might throw

    // And then when we're happy it has succeeded:
    scoper.active = false; // Leave the file open

Received on 2023-06-11 15:57:25