C++ Logo

std-discussion

Advanced search

Re: Some feedback on scope guards

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Thu, 13 Apr 2023 20:14:16 -0400
On Thu, Apr 13, 2023 at 3:57 PM Ville Voutilainen
<ville.voutilainen_at_[hidden]> wrote:
>
> On Thu, 13 Apr 2023 at 22:53, Jason McKesson <jmckesson_at_[hidden]> wrote:
> >
> > On Thu, Apr 13, 2023 at 3:28 PM Ville Voutilainen
> > <ville.voutilainen_at_[hidden]> wrote:
> > >
> > > On Thu, 13 Apr 2023 at 22:01, Jason McKesson via Std-Discussion
> > > <std-discussion_at_[hidden]> wrote:
> > >
> > > > Considering how difficult it is to answer the basic question in
> > > > coroutines without an explicit `try` block... maybe we should just not
> > > > support these things? Maybe we should just encourage people to use
> > > > `try/catch` blocks if they need to check for scope failure. Yes, it's
> > > > not as visually pleasing, but it solves the problem.
> > >
> > > That solution doesn't work, because you can exit scopes with return,
> > > break, and goto as well,
> > > and the whole point of these scope guards is that they are able to run
> > > their cleanup regardless
> > > of how you do the scope exit. And for scope_fail, its purpose is
> > > specifically that you don't
> > > have to catch and rethrow if your function doesn't want to handle
> > > exception. So that's
> > > a complete non-solution.
> >
> > So maybe `catch noexcept` could be added to the language. Instead of
> > catching an exception emitted by a `try` block, it catches on any exit
> > from that scope that isn't an exception.
>
> To do what? If I want to program in a language that doesn't destroy
> things automatically,
> I know where to find java. These are RAII wrappers, and they're
> already far superior to such
> a language facility.

But we're not talking about RAII wrappers. `unqiue_resource` is a RAII
wrapper, and it works perfectly fine in coroutines.

We're talking about scope_success/fail. These are not RAII-wrappers of
some resource that needs cleanup. These are tools for executing a
given function if a block of code exits via success or failure. The
object(s) they operate on is not actually part of those "wrappers".

The language already has a tool to allow you to execute some code if a
block exits via failure: `try/catch`. If we need a tool to allow you
to execute code on the successful exit of a block, why not just adjust
that tool?

Plus, C++23 is getting `std::expected`, which now makes "return
unexpected(...);" into the conceptual equivalent of a *failure* state.
As far as the language is concerned, this is a success. But as far as
the idea of what `std::expected` is doing, it is a failure.

So it's really questionable what `scope_success/fail` means these days.

Received on 2023-04-14 00:14:29