LLVM 22.0.0git
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/// \file
10/// This file defines the make_scope_exit function, which executes user-defined
11/// cleanup logic at scope exit.
12///
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_ADT_SCOPEEXIT_H
16#define LLVM_ADT_SCOPEEXIT_H
17
19#include <utility>
20
21namespace llvm {
22
23template <typename Callable> class scope_exit {
24 Callable ExitFunction;
25 bool Engaged = true; // False once moved-from or release()d.
26
27public:
28 template <typename Fp>
29 explicit scope_exit(Fp &&F) : ExitFunction(std::forward<Fp>(F)) {}
30
32 : ExitFunction(std::move(Rhs.ExitFunction)), Engaged(Rhs.Engaged) {
33 Rhs.release();
34 }
35 scope_exit(const scope_exit &) = delete;
37 scope_exit &operator=(const scope_exit &) = delete;
38
39 void release() { Engaged = false; }
40
42 if (Engaged)
43 ExitFunction();
44 }
45};
46
47template <typename Callable> scope_exit(Callable) -> scope_exit<Callable>;
48
49// Keeps the callable object that is passed in, and execute it at the
50// destruction of the returned object (usually at the scope exit where the
51// returned object is kept).
52//
53// Interface is specified by p0052r2.
54template <typename Callable>
55[[nodiscard]]
56LLVM_DEPRECATED("Prefer calling the constructor of llvm::scope_exit directly.",
57 "scope_exit") auto make_scope_exit(Callable &&F) {
58 // TODO(LLVM 24): Remove this function.
59 return scope_exit(std::forward<Callable>(F));
60}
61
62} // end namespace llvm
63
64#endif
#define LLVM_DEPRECATED(MSG, FIX)
Definition Compiler.h:252
#define F(x, y, z)
Definition MD5.cpp:54
scope_exit & operator=(const scope_exit &)=delete
scope_exit(const scope_exit &)=delete
scope_exit(Fp &&F)
Definition ScopeExit.h:29
scope_exit(scope_exit &&Rhs)
Definition ScopeExit.h:31
scope_exit & operator=(scope_exit &&)=delete
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
scope_exit(Callable) -> scope_exit< Callable >
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1915
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:870