JSON Voorhees
Killer JSON for C++
Loading...
Searching...
No Matches
scope_exit.hpp
Go to the documentation of this file.
1/// \file jsonv/detail/scope_exit.hpp
2/// Definition of the \c on_scope_exit utility.
3///
4/// Copyright (c) 2015 by Travis Gockel. All rights reserved.
5///
6/// This program is free software: you can redistribute it and/or modify it under the terms of the Apache License
7/// as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later
8/// version.
9///
10/// \author Travis Gockel (travis@gockelhut.com)
11#pragma once
12
13#include <jsonv/config.hpp>
14
15#include <type_traits>
16#include <utility>
17
18namespace jsonv::detail
19{
20
21template <typename Function>
22class scope_exit_invoker
23{
24public:
25 explicit scope_exit_invoker(Function&& func) :
26 _func(std::move(func)),
27 _responsible(true)
28 { }
29
30 scope_exit_invoker(scope_exit_invoker&& src) noexcept(std::is_nothrow_move_constructible_v<Function>) :
31 _func(std::move(src._func)),
32 _responsible(src._responsible)
33 {
34 src._responsible = false;
35 }
36
37 scope_exit_invoker(const scope_exit_invoker&) = delete;
38 scope_exit_invoker& operator=(const scope_exit_invoker&) = delete;
39 scope_exit_invoker& operator=(scope_exit_invoker&&) = delete;
40
41 ~scope_exit_invoker()
42 {
43 if (_responsible)
44 _func();
45 }
46
47 void release()
48 {
49 _responsible = false;
50 }
51
52private:
53 Function _func;
54 bool _responsible;
55};
56
57template <typename Function>
59scope_exit_invoker<Function> on_scope_exit(Function func)
60{
61 return scope_exit_invoker<Function>(std::move(func));
62}
63
64}
Copyright (c) 2014-2020 by Travis Gockel.
#define JSONV_NODISCARD
Warn if the caller discards the result of this function.
Definition config.hpp:132
STL namespace.