Boost logo

Boost :

From: Andrey Semashev (andysem_at_[hidden])
Date: 2005-09-23 16:20:49

>> The more common use case is to create initially disabled guard and
>> then, depending on some condition, activate it. I've had the need of
>> such functionality several times.
> I've tried to construct imaginary use cases that illustrate this, but
> in my experience, it is usually not possible to create the guard
> before acquiring the resource, because the guard needs to store the
> acquired resource.
> Something like
> FILE * f = fopen( ... );
> if( f == 0 ) throw ...;
> scoped_guard file_closer = make_guard( fclose, f );
> Even if the fopen is conditional, I can't create the guard and 'arm'
> it later, unless 'arm' takes parameters.

In this (or similar) case I might rather make a tiny wrapper around FILE*
instead of guard. But that depends on the context and other factors. In this
particular case "arm" would be useless.

> Your examples don't carry enough context for me to be able to
> understand them. I'm pretty sure I can refactor every 'arm'ing
> example into one that doesn't need 'arm', but the interesting
> question is whether this refactoring would improve the code. Without
> some real examples, I can't answer this for myself.

I cannot show the real code since it's commercial. Though I can tell you
that this code wouldn't become better if I tried to avoid the scope guard.
Note that the place of creation (and therefore of destruction) in these
examples (especially in the second one) is important and the guard cannot be
created in place where it should be armed. So either create and arm guard
separatedly, or try to avoid it at all. The latter makes the code worse.

In my experience the use of this feature was rather specific but it was very
useful though. And I don't see any reason why it shouldn't be included in
the implementation. I can try to make up a more generic example but I need
more time.

Boost list run by bdawes at, gregod at, cpdaniel at, john at