LLVM  10.0.0svn
ScopeExit.h
Go to the documentation of this file.
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 
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 
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>
58 make_scope_exit(Callable &&F) {
60  std::forward<Callable>(F));
61 }
62 
63 } // end namespace llvm
64 
65 #endif
scope_exit(scope_exit &&Rhs)
Definition: ScopeExit.h:33
This class represents lattice values for constants.
Definition: AllocatorList.h:23
LLVM_NODISCARD detail::scope_exit< typename std::decay< Callable >::type > make_scope_exit(Callable &&F)
Definition: ScopeExit.h:58
F(f)
Definition: BitVector.h:937
scope_exit & operator=(scope_exit &&)=delete
#define LLVM_NODISCARD
LLVM_NODISCARD - Warn if a type or return value is discarded.
Definition: Compiler.h:153