liblcf
scope_guard.h
Go to the documentation of this file.
1 /*
2  * This file is part of liblcf. Copyright (c) 2020 liblcf authors.
3  * https://github.com/EasyRPG/liblcf - https://easyrpg.org
4  *
5  * liblcf is Free/Libre Open Source Software, released under the MIT License.
6  * For the full copyright and license information, please view the COPYING
7  * file that was distributed with this source code.
8  */
9 
10 #ifndef LCF_SCOPE_GUARD_H
11 #define LCF_SCOPE_GUARD_H
12 #include <utility>
13 
14 template <typename F>
15 class ScopeGuard {
16  public:
17  ScopeGuard() = default;
18  explicit ScopeGuard(const F& f) : _f(f), _active(true) {}
19  explicit ScopeGuard(F&& f) : _f(std::move(f)), _active(true) {}
20 
21  ScopeGuard(const ScopeGuard&) = delete;
22  ScopeGuard& operator=(const ScopeGuard&) = delete;
23 
25  : _f(std::move(o._f)), _active(true) { o._active = false; }
26  ScopeGuard& operator=(ScopeGuard&&) = delete;
27 
28  ~ScopeGuard() { Fire(); }
29 
30  void Fire() noexcept;
31  void Dismiss() noexcept;
32  bool IsActive() noexcept;
33  private:
34  F _f;
35  bool _active = false;
36 };
37 
38 template <typename F>
39 inline ScopeGuard<F> makeScopeGuard(F&& f) {
40  return ScopeGuard<F>(std::forward<F>(f));
41 }
42 
43 template <typename F>
44 inline void ScopeGuard<F>::Fire() noexcept {
45  if (_active) {
46  _f();
47  Dismiss();
48  }
49 }
50 
51 template <typename F>
52 inline void ScopeGuard<F>::Dismiss() noexcept {
53  _active = false;
54 }
55 
56 template <typename F>
57 inline bool ScopeGuard<F>::IsActive() noexcept {
58  return _active;
59 }
60 
61 #endif
bool IsActive() noexcept
Definition: scope_guard.h:57
ScopeGuard(F &&f)
Definition: scope_guard.h:19
void Dismiss() noexcept
Definition: scope_guard.h:52
bool _active
Definition: scope_guard.h:35
ScopeGuard(ScopeGuard &&o)
Definition: scope_guard.h:24
ScopeGuard(const F &f)
Definition: scope_guard.h:18
ScopeGuard & operator=(const ScopeGuard &)=delete
void Fire() noexcept
Definition: scope_guard.h:44
ScopeGuard()=default
ScopeGuard< F > makeScopeGuard(F &&f)
Definition: scope_guard.h:39