Turi Create
4.0
try_finally.hpp
1
/* Copyright © 2017 Apple Inc. All rights reserved.
2
*
3
* Use of this source code is governed by a BSD-3-clause license that can
4
* be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
5
*/
6
#ifndef TURI_TRY_FINALLY_H_
7
#define TURI_TRY_FINALLY_H_
8
9
#include <vector>
10
#include <functional>
11
12
namespace
turi
{
13
14
/**
15
* \ingroup util
16
* Class to use the garuanteed destructor call of a scoped variable
17
* to simulate a try...finally block. This is the standard C++ way
18
* of doing that.
19
*
20
* Use:
21
*
22
* When you want to ensure something is executed, even when
23
* exceptions are present, create a scoped_finally structure and add
24
* the appropriate cleanup functions to it. When this structure
25
* goes out of scope, either due to an exception or the code leaving
26
* that scope, these functions are executed.
27
*
28
* This is useful for cleaning up locks, etc.
29
*/
30
class
scoped_finally
{
31
public
:
32
33
scoped_finally
()
34
{}
35
36
scoped_finally
(std::vector<std::function<
void
()> > _f_v)
37
: f_v(_f_v)
38
{}
39
40
scoped_finally
(std::function<
void
()> _f)
41
: f_v{_f}
42
{}
43
44
void
add(std::function<
void
()> _f) {
45
f_v.push_back(_f);
46
}
47
48
void
execute_and_clear() {
49
for
(
size_t
i = f_v.size(); (i--) != 0;) {
50
f_v[i]();
51
}
52
f_v.clear();
53
}
54
55
~
scoped_finally
() {
56
execute_and_clear();
57
}
58
59
private
:
60
std::vector<std::function<void()> > f_v;
61
};
62
63
}
64
65
66
67
68
69
70
71
#endif
/* _TRY_FINALLY_H_ */
turi::scoped_finally
Definition:
try_finally.hpp:30
turi
SKD.
Definition:
capi_initialization.hpp:11
core
util
try_finally.hpp
Generated by
1.8.13