1 //===- llvm/ADT/ScopeExit.h - Execute code at scope exit --------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file defines the make_scope_exit function, which executes user-defined
10 // cleanup logic at scope exit.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_ADT_SCOPE_EXIT_H
15 #define LLVM_ADT_SCOPE_EXIT_H
17 #include "llvm/Support/Compiler.h"
19 #include <type_traits>
25 template <typename Callable
> class scope_exit
{
26 Callable ExitFunction
;
27 bool Engaged
= true; // False once moved-from or release()d.
30 template <typename Fp
>
31 explicit scope_exit(Fp
&&F
) : ExitFunction(std::forward
<Fp
>(F
)) {}
33 scope_exit(scope_exit
&&Rhs
)
34 : ExitFunction(std::move(Rhs
.ExitFunction
)), Engaged(Rhs
.Engaged
) {
37 scope_exit(const scope_exit
&) = delete;
38 scope_exit
&operator=(scope_exit
&&) = delete;
39 scope_exit
&operator=(const scope_exit
&) = delete;
41 void release() { Engaged
= false; }
49 } // end namespace detail
51 // Keeps the callable object that is passed in, and execute it at the
52 // destruction of the returned object (usually at the scope exit where the
53 // returned object is kept).
55 // Interface is specified by p0052r2.
56 template <typename Callable
>
57 LLVM_NODISCARD
detail::scope_exit
<typename
std::decay
<Callable
>::type
>
58 make_scope_exit(Callable
&&F
) {
59 return detail::scope_exit
<typename
std::decay
<Callable
>::type
>(
60 std::forward
<Callable
>(F
));
63 } // end namespace llvm