]> granicus.if.org Git - icinga2/blob - lib/base/defer.hpp
Merge pull request #7185 from Icinga/bugfix/gelfwriter-wrong-log-facility
[icinga2] / lib / base / defer.hpp
1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
2
3 #ifndef DEFER
4 #define DEFER
5
6 #include <functional>
7 #include <utility>
8
9 namespace icinga
10 {
11
12 /**
13  * An action to be executed at end of scope.
14  *
15  * @ingroup base
16  */
17 class Defer
18 {
19 public:
20         inline
21         Defer(std::function<void()> func) : m_Func(std::move(func))
22         {
23         }
24
25         Defer(const Defer&) = delete;
26         Defer(Defer&&) = delete;
27         Defer& operator=(const Defer&) = delete;
28         Defer& operator=(Defer&&) = delete;
29
30         inline
31         ~Defer()
32         {
33                 try {
34                         m_Func();
35                 } catch (...) {
36                         // https://stackoverflow.com/questions/130117/throwing-exceptions-out-of-a-destructor
37                 }
38         }
39
40 private:
41         std::function<void()> m_Func;
42 };
43
44 }
45
46 #endif /* DEFER */