| 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 |
#pragma once |
| 14 |
#include <type_traits> |
| 15 |
#include <utility> |
| 16 |
|
| 17 |
namespace lsp |
| 18 |
{ |
| 19 |
namespace detail |
| 20 |
{ |
| 21 |
|
| 22 |
template<typename Callable> |
| 23 |
class scope_exit |
| 24 |
{ |
| 25 |
Callable ExitFunction; |
| 26 |
bool Engaged = true; // False once moved-from or release()d. |
| 27 |
|
| 28 |
public: |
| 29 |
template<typename Fp> |
| 30 |
explicit scope_exit(Fp&& F) : ExitFunction(std::forward<Fp>(F)) |
| 31 |
{ |
| 32 |
} |
| 33 |
|
| 34 |
scope_exit(scope_exit&& Rhs) : ExitFunction(std::move(Rhs.ExitFunction)), Engaged(Rhs.Engaged) |
| 35 |
{ |
| 36 |
Rhs.release(); |
| 37 |
} |
| 38 |
scope_exit(scope_exit const&) = delete; |
| 39 |
scope_exit& operator=(scope_exit&&) = delete; |
| 40 |
scope_exit& operator=(scope_exit const&) = delete; |
| 41 |
|
| 42 |
void release() |
| 43 |
{ |
| 44 |
Engaged = false; |
| 45 |
} |
| 46 |
|
| 47 |
~scope_exit() |
| 48 |
{ |
| 49 |
if (Engaged) |
| 50 |
{ |
| 51 |
ExitFunction(); |
| 52 |
} |
| 53 |
} |
| 54 |
}; |
| 55 |
|
| 56 |
} // end namespace detail |
| 57 |
|
| 58 |
// Keeps the callable object that is passed in, and execute it at the |
| 59 |
// destruction of the returned object (usually at the scope exit where the |
| 60 |
// returned object is kept). |
| 61 |
// |
| 62 |
// Interface is specified by p0052r2. |
| 63 |
template<typename Callable> |
| 64 |
detail::scope_exit<typename std::decay<Callable>::type> make_scope_exit(Callable&& F) |
| 65 |
{ |
| 66 |
return detail::scope_exit<typename std::decay<Callable>::type>(std::forward<Callable>(F)); |
| 67 |
} |
| 68 |
|
| 69 |
} // end namespace lsp |