KSSUtil  v14.2.0
C++ general utility library
raii.hpp
Go to the documentation of this file.
1 //
2 // raii.hpp
3 //
4 // Created by Steven W. Klassen on 2016-08-26.
5 // Copyright © 2016 Klassen Software Solutions. All rights reserved.
6 // Licensing follows the MIT License.
7 //
8 
14 #ifndef kssutil_raii_h
15 #define kssutil_raii_h
16 
17 #include <functional>
18 
19 namespace kss { namespace util {
20 
54  class RAII {
55  public:
56  typedef std::function<void()> lambda_t;
57 
63  RAII(const lambda_t& initCode, const lambda_t& cleanupCode) : _cleanupCode(cleanupCode) {
64  initCode();
65  }
66 
67  RAII(const lambda_t& initCode, lambda_t&& cleanupCode) : _cleanupCode(move(cleanupCode)) {
68  initCode();
69  }
70 
71  ~RAII() {
72  _cleanupCode();
73  }
74 
75  RAII& operator=(const RAII&) = delete;
76  RAII& operator=(RAII&&) = delete;
77 
78  private:
79  lambda_t _cleanupCode;
80  };
81 
82 
89  class Finally : public RAII {
90  public:
91  explicit Finally(const lambda_t& code) : RAII([]{}, code) {}
92  explicit Finally(lambda_t&& code) : RAII([]{}, move(code)) {}
93  };
94 
95 }}
96 
97 #endif
kss::util::RAII::RAII
RAII(const lambda_t &initCode, lambda_t &&cleanupCode)
Definition: raii.hpp:67
kss::util::RAII::operator=
RAII & operator=(const RAII &)=delete
kss::util::RAII::RAII
RAII(const lambda_t &initCode, const lambda_t &cleanupCode)
Definition: raii.hpp:63
kss::util::Finally::Finally
Finally(const lambda_t &code)
Definition: raii.hpp:91
kss::util::Finally
Implementation of a "finally" block.
Definition: raii.hpp:89
kss::util::RAII
Implementation of the RAII pattern.
Definition: raii.hpp:54
kss::util::Finally::Finally
Finally(lambda_t &&code)
Definition: raii.hpp:92
kss::util::RAII::lambda_t
std::function< void()> lambda_t
Definition: raii.hpp:56
kss
All Klassen Software Solutions libraries begin with this namespace.
Definition: add_rel_ops.hpp:19
kss::util::RAII::~RAII
~RAII()
Definition: raii.hpp:71