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 <utility>
16
17namespace jsonv::detail
18{
19
20template <typename Function>
21class scope_exit_invoker
22{
23public:
24 explicit scope_exit_invoker(Function&& func) :
25 _func(std::move(func)),
26 _responsible(true)
27 { }
28
29 scope_exit_invoker(scope_exit_invoker&& src) :
30 _func(std::move(src._func)),
31 _responsible(src._responsible)
32 {
33 src._responsible = false;
34 }
35
36 scope_exit_invoker(const scope_exit_invoker&) = delete;
37 scope_exit_invoker& operator=(const scope_exit_invoker&) = delete;
38 scope_exit_invoker& operator=(scope_exit_invoker&&) = delete;
39
40 ~scope_exit_invoker()
41 {
42 if (_responsible)
43 _func();
44 }
45
46 void release()
47 {
48 _responsible = false;
49 }
50
51private:
52 Function _func;
53 bool _responsible;
54};
55
56template <typename Function>
57scope_exit_invoker<Function> on_scope_exit(Function func)
58{
59 return scope_exit_invoker<Function>(std::move(func));
60}
61
62}
Copyright (c) 2014-2020 by Travis Gockel.
STL namespace.