]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/ADT/ScopeExit.h
Fix a memory leak in if_delgroups() introduced in r334118.
[FreeBSD/FreeBSD.git] / contrib / llvm / include / llvm / ADT / ScopeExit.h
1 //===- llvm/ADT/ScopeExit.h - Execute code at scope exit --------*- C++ -*-===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the make_scope_exit function, which executes user-defined
10 // cleanup logic at scope exit.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_ADT_SCOPE_EXIT_H
15 #define LLVM_ADT_SCOPE_EXIT_H
16
17 #include "llvm/Support/Compiler.h"
18
19 #include <type_traits>
20 #include <utility>
21
22 namespace llvm {
23 namespace detail {
24
25 template <typename Callable> class scope_exit {
26   Callable ExitFunction;
27   bool Engaged = true; // False once moved-from or release()d.
28
29 public:
30   template <typename Fp>
31   explicit scope_exit(Fp &&F) : ExitFunction(std::forward<Fp>(F)) {}
32
33   scope_exit(scope_exit &&Rhs)
34       : ExitFunction(std::move(Rhs.ExitFunction)), Engaged(Rhs.Engaged) {
35     Rhs.release();
36   }
37   scope_exit(const scope_exit &) = delete;
38   scope_exit &operator=(scope_exit &&) = delete;
39   scope_exit &operator=(const scope_exit &) = delete;
40
41   void release() { Engaged = false; }
42
43   ~scope_exit() {
44     if (Engaged)
45       ExitFunction();
46   }
47 };
48
49 } // end namespace detail
50
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).
54 //
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));
61 }
62
63 } // end namespace llvm
64
65 #endif