-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathfinally.h
93 lines (77 loc) · 2.58 KB
/
finally.h
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/////////////////////////////////////////////////////////////////////////////
// Copyright (c) Electronic Arts Inc. All rights reserved.
/////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// eastl::finally is an implementation of the popular cpp idiom RAII - Resource
// Acquisition Is Initialization. eastl::finally guarantees that the user
// provided callable will be executed upon whatever mechanism is used to leave
// the current scope. This can guard against user errors but this is a popular
// technique to write robust code in execution environments that have exceptions
// enabled.
//
// Example:
// void foo()
// {
// void* p = malloc(128);
// auto _ = eastl::make_finally([&] { free(p); });
//
// // Code that may throw an exception...
//
// } // eastl::finally guaranteed to call 'free' at scope exit.
//
// References:
// * https://www.bfilipek.com/2017/04/finalact.html
///////////////////////////////////////////////////////////////////////////////
#ifndef EASTL_FINALLY_H
#define EASTL_FINALLY_H
#if defined(EASTL_PRAGMA_ONCE_SUPPORTED)
#pragma once
#endif
#include <eastl/internal/config.h>
#include <eastl/internal/move_help.h>
#include <eastl/type_traits.h>
namespace eastl
{
///////////////////////////////////////////////////////////////////////////
// finally
//
// finally is the type that calls the users callback on scope exit.
//
template <typename Functor>
class finally
{
static_assert(!eastl::is_lvalue_reference_v<Functor>, "eastl::finally requires the callable is passed as an rvalue reference.");
Functor m_functor;
bool m_engaged = false;
public:
finally(Functor f) : m_functor(eastl::move(f)), m_engaged(true) {}
finally(finally&& other) : m_functor(eastl::move(other.m_functor)), m_engaged(other.m_engaged)
{
other.dismiss();
}
~finally() { execute(); }
finally(const finally&) = delete;
finally& operator=(const finally&) = delete;
finally& operator=(finally&&) = delete;
inline void dismiss() { m_engaged = false; }
inline void execute()
{
if (m_engaged)
m_functor();
dismiss();
}
};
///////////////////////////////////////////////////////////////////////////
// make_finally
//
// this utility function is the standard mechansim to perform the required
// type deduction on the users provided callback inorder to create a
// 'finally' object.
//
template <typename F>
auto make_finally(F&& f)
{
return finally<F>(eastl::forward<F>(f));
}
}
#endif // EASTL_FINALLY_H