C++ Logo

std-discussion

Advanced search

Re: Some feedback on scope guards

From: Thiago Macieira <thiago_at_[hidden]>
Date: Fri, 07 Apr 2023 19:49:48 -0300
On Friday, 7 April 2023 14:31:46 -03 Andrey Semashev via Std-Discussion wrote:
> I think this issue needs to be addressed in the TS before inclusion into
> the main standard. As a possible solution, I proposed the following idea:

The standard solution does not need your suggested implementation details. It
just needs to describe the expected behaviour and require that the
implementations do it properly. They may have other means of achieving the
same result.

A set of simple unit tests from Boost's learnings would be welcome, though.

> 1. I think, there should be a way to activate a deactivated scope guard.
> Also, there should be a way to construct an initially inactive scope
> guard.

Agreed.

> 2. For scope_success/scope_fail, it would be useful to be able to
> specify a user-defined condition function for detecting the failure
> condition. This is useful in cases when the failure is indicated not via
> an exception but via other means, such as returning an error code. The
> idea was implemented in Boost.Scope, where checking for an exception is
> merely a default failure condition, with the user being able to specify
> his own.

For most cases, this can be implemented already, with the ability to
deactivate a scope, because the typical use of such guards is to have them
execute on early returns. At the moment when we've achieved success, it can be
then dismissed -- compiler optimisations detecting such conditions would be
welcome too.

However, I do see agree that some more scenarios can't be written like
described above. They'd have to do some arm-twisting to get the failing
conditions early, before dismissal... though reactivating a dismissed guard
could allow further options.

For those scenarios, why can't the user-provided lambda that is executed
decide whether to do anything at all? Why do we need to give the scope guard
object two lambdas: one to decide whether to run and the other to run?

> 3. There is room for a scope guard that is more lightweight than
> scope_exit. Specifically, a scope guard that unconditionally calls its
> action, is not moveable and cannot be deactivated. Think of it as
> lock_guard compared to unique_lock. In my experience, the majority of
> scope guards don't need to be able to be (de)activated or moved, so this
> optimization would be useful.

Can this simply be QoI? The control variable of a dismissable scope guard that
isn't dismissed can itself be garbage-collected after optimisation passes such
as constant propagation and dead code elimination.
-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
   Software Architect - Intel DCAI Cloud Engineering

Received on 2023-04-07 22:49:51