1
0
Fork 0
mirror of https://github.com/juce-framework/JUCE.git synced 2026-01-10 23:44:24 +00:00

Functional: Add ScopeGuard implementation

This commit is contained in:
reuk 2022-11-02 11:32:58 +00:00
parent cbf59e185f
commit 0fbd7d7b3f
No known key found for this signature in database
GPG key ID: 9ADCD339CFC98A11
2 changed files with 27 additions and 7 deletions

View file

@ -86,4 +86,31 @@ Object withMember (Object copy, Member OtherObject::* member, Other&& value)
return copy;
}
/** An easy way to ensure that a function is called at the end of the current
scope.
Usage:
@code
{
if (flag == true)
return;
// While this code executes, flag is true e.g. to prevent reentrancy
flag = true;
// When we exit this scope, flag must be false
const ScopeGuard scope { [&] { flag = false; } };
if (checkInitialCondition())
return; // Scope's lambda will fire here...
if (checkCriticalCondition())
throw std::runtime_error{}; // ...or here...
doWorkHavingEstablishedPreconditions();
} // ...or here!
@endcode
*/
template <typename Fn> struct ScopeGuard : Fn { ~ScopeGuard() { Fn::operator()(); } };
template <typename Fn> ScopeGuard (Fn) -> ScopeGuard<Fn>;
} // namespace juce