• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2016-present, Facebook, Inc.
3  * All rights reserved.
4  *
5  * This source code is licensed under both the BSD-style license (found in the
6  * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7  * in the COPYING file in the root directory of this source tree).
8  */
9 #pragma once
10 
11 #include <utility>
12 
13 namespace pzstd {
14 
15 /**
16  * Dismissable scope guard.
17  * `Function` must be callable and take no parameters.
18  * Unless `dissmiss()` is called, the callable is executed upon destruction of
19  * `ScopeGuard`.
20  *
21  * Example:
22  *
23  *   auto guard = makeScopeGuard([&] { cleanup(); });
24  */
25 template <typename Function>
26 class ScopeGuard {
27   Function function;
28   bool dismissed;
29 
30  public:
ScopeGuard(Function && function)31   explicit ScopeGuard(Function&& function)
32       : function(std::move(function)), dismissed(false) {}
33 
dismiss()34   void dismiss() {
35     dismissed = true;
36   }
37 
~ScopeGuard()38   ~ScopeGuard() noexcept {
39     if (!dismissed) {
40       function();
41     }
42   }
43 };
44 
45 /// Creates a scope guard from `function`.
46 template <typename Function>
makeScopeGuard(Function && function)47 ScopeGuard<Function> makeScopeGuard(Function&& function) {
48   return ScopeGuard<Function>(std::forward<Function>(function));
49 }
50 }
51