C++ Logo

std-discussion

Advanced search

Re: Some feedback on scope guards

From: Edward Catmur <ecatmur_at_[hidden]>
Date: Fri, 14 Apr 2023 09:44:26 -0300
On Fri, 14 Apr 2023, 09:35 Andrey Semashev via Std-Discussion, <
std-discussion_at_[hidden]> wrote:

> On 4/14/23 15:29, Ville Voutilainen wrote:
> > On Fri, 14 Apr 2023 at 14:47, Andrey Semashev via Std-Discussion
> > <std-discussion_at_[hidden]> wrote:
> >
> >>> > > If it's for RAII, then plain scope_guard should be fine (even
> if
> >>> a bit misused; a class type is not a scope). scope_success and
> >>> scope_failure would not make much sense as data members unless
> >>> you're writing another success/failure scope guard class (what I
> >>> meant by composability).
> >>> >
> >>> > That I can probably live with.
> >>>
> >>> ..except.. I don't think that's wise. I can easily imagine uses
> where
> >>> I create an array of scope_fails, a tuple of scope fails, or even
> >>> a vector of scope_fails. I find it perfectly reasonable to expect
> such
> >>> composition to Just Work.
> >>>
> >>> Those can trivially be replaced with a single scope_fail referencing an
> >>> array, tuple or vector of callbacks.
> >>
> >> I think the point was that it is unexpected that this wouldn't work
> >> without this workaround.
> >
> > Well, it's easy enough to play with that, either using boost or by
> > just using the TS implementation
> > that is in libstdc++. The suggestion by Edward sounds semi-plausible..
> > but the concern remains,
> > especially for tuple, that the end result is much harder to use than
> > just a straightforward tuple
> > of scope_fails.
>

If you allow tuple, then you have to allow vector, and since a vector can
be moved without moving its elements you then have the problem of
(success/failure) scope guards being destroyed from a scope other than the
one they were constructed in.

I'll add that the replacement code suggested by Edward is not equivalent
> to the original as you lose the ability to (de)activate individual scope
> guards. With scope guards supporting custom failure conditions, you also
> lose that.
>

Yes. Users sophisticated enough to want to create tuples of scope guards
can work out how to create their own flag variables, I think. It'd be nice
if we had variable declarations as pack expansions, though, since that
would fix the problem entirely.

>

Received on 2023-04-14 12:44:44