Nix
2.36.0
Nix, the purely functional package manager; unstable internal interfaces
Toggle main menu visibility
Loading...
Searching...
No Matches
finally.hh
Go to the documentation of this file.
1
#pragma once
3
4
#include <utility>
5
#include <cassert>
6
#include <exception>
7
8
namespace
nix {
9
13
template
<
typename
Fn>
14
class
[[nodiscard(
"Finally values must be used"
)]] Finally
15
{
16
private
:
17
Fn fun;
18
bool
movedFrom =
false
;
19
20
public
:
21
Finally(Fn fun)
22
: fun(std::move(fun))
23
{
24
}
25
26
// Copying Finallys is definitely not a good idea and will cause them to be
27
// called twice.
28
Finally(Finally & other) =
delete
;
29
30
// NOTE: Move constructor can be nothrow if the callable type is itself nothrow
31
// move-constructible.
32
Finally(Finally && other)
noexcept
(std::is_nothrow_move_constructible_v<Fn>)
33
: fun(std::move(other.fun))
34
{
35
other.movedFrom =
true
;
36
}
37
38
~Finally()
noexcept
(
false
)
39
{
40
try
{
41
if
(!movedFrom)
42
fun();
43
}
catch
(...) {
44
// finally may only throw an exception if exception handling is not already
45
// in progress. if handling *is* in progress we have to return cleanly here
46
// but are still prohibited from doing so since eating the exception would,
47
// in almost all cases, mess up error handling even more. the only good way
48
// to handle this is to abort entirely and leave a message, so we'll assert
49
// (and rethrow anyway, just as a defense against possible NASSERT builds.)
50
if
(std::uncaught_exceptions()) {
51
assert(
false
&&
52
"Finally function threw an exception during exception handling. "
53
"this is not what you want, please use some other methods (like "
54
"std::promise or async) instead."
);
55
}
56
throw
;
57
}
58
}
59
};
60
61
}
// namespace nix
libutil
include
nix
util
finally.hh
Generated by
1.18.0