-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathraii.hpp
More file actions
73 lines (57 loc) · 1.54 KB
/
raii.hpp
File metadata and controls
73 lines (57 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#pragma once
// std
#include <functional>
#include <type_traits>
namespace util {
/// a generalized wrapper for RAII managing ownership/cleanup
/// of an instance of \tparam T t:
/// - adopts a resource on construction
/// - cleans up the resource on destruction
///
/// must supply appropriate callable for
/// cleanup of the managed resource
template <
typename T,
typename = std::enable_if_t<std::is_pointer_v<T>>
>
class RAII
{
public:
using CleanupF = std::function<void(T)>;
/// adopt an already existing resource and supply
/// a cleanup function
RAII( T __managed, CleanupF cleanup )
: _managed( __managed )
, _cleanup( cleanup )
{}
/// cannot copy
RAII(const RAII&) = delete;
RAII& operator=(const RAII&) = delete;
// can move
RAII(RAII&& m)
{
_managed = m._managed;
_cleanup = m._cleanup;
m._managed = nullptr;
m._cleanup = {};
}
RAII& operator=(RAII&& m)
{
_managed = m._managed;
_cleanup = m._cleanup;
m._managed = nullptr;
m._cleanup = {};
return *this;
}
~RAII()
{
if ( _cleanup )
_cleanup(_managed);
}
const T& managed() const { return _managed; }
T& managed() { return _managed; }
private:
mutable T _managed;
CleanupF _cleanup;
};
}