C++ Logo


Advanced search

Re: Some feedback on scope guards

From: Andrey Semashev <andrey.semashev_at_[hidden]>
Date: Thu, 13 Apr 2023 23:44:25 +0300
On 4/13/23 22:01, Jason McKesson via Std-Discussion wrote:
> So given all of that, here's an odd question: Why are we doing this at all?
> Think about it: the original problem is to detect whether an exception
> is being fired from within some bound scope and execute some code
> based on that. But we already have a tool for that: `try/catch`.
> Oh sure, it requires creating an explicit scope with curly braces. And
> it puts the fail-handling code below the block that might throw rather
> than near the objects that it will act on. But ultimately, it solves
> the problem.

What if you already have a try/catch? With multiple catch blocks? What
if there are multiple try/catch blocks within the guarded scope?

> And for the success state... just put the code below there; if an
> exception is emitted, it will never be executed.

Similarly, what if there are multiple returns?

> So overall, the main thing we get out of `scope_success/fail` is
> changing the locality of the fail/success code.

Apart from the above questions, I consider the correct locality and code
clarity an important property of scope guards, which significantly
simplifies code maintenance.

> 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.

There are multiple solutions to the problem, of course. One of them is
not using exceptions, another one is not using coroutines. :) I think,
looking for solutions to problems imposed by those features (each of
them being useful in their own regard) and improving the language to
better handle corner cases is important and desirable.

Received on 2023-04-13 20:44:29