Botan 3.11.0
Crypto and TLS for C&
scoped_cleanup.h
Go to the documentation of this file.
1/*
2* (C) 2023-2024 René Meusel - Rohde & Schwarz Cybersecurity
3*
4* Botan is released under the Simplified BSD License (see license.txt)
5*/
6
7#ifndef BOTAN_SCOPED_CLEANUP_H_
8#define BOTAN_SCOPED_CLEANUP_H_
9
10#include <concepts>
11#include <optional>
12#include <utility>
13
14namespace Botan {
15
16/**
17 * @brief Helper class to create a RAII-style cleanup callback
18 *
19 * Ensures that the cleanup callback given in the object's constructor is called
20 * when the object is destroyed. Use this to ensure some cleanup code runs when
21 * leaving the current scope.
22 */
23template <std::invocable FunT>
24class scoped_cleanup final {
25 public:
26 explicit scoped_cleanup(FunT cleanup) : m_cleanup(std::move(cleanup)) {}
27
30
31 scoped_cleanup(scoped_cleanup&& other) noexcept : m_cleanup(std::move(other.m_cleanup)) { other.disengage(); }
32
34 if(this != &other) {
35 m_cleanup = std::move(other.m_cleanup);
36 other.disengage();
37 }
38 return *this;
39 }
40
42 if(m_cleanup.has_value()) {
43 (*m_cleanup)(); // NOLINT(bugprone-exception-escape) clang-tidy bug
44 }
45 }
46
47 /**
48 * Disengage the cleanup callback, i.e., prevent it from being called
49 */
50 void disengage() noexcept { m_cleanup.reset(); }
51
52 private:
53 std::optional<FunT> m_cleanup;
54};
55
56} // namespace Botan
57
58#endif
scoped_cleanup(const scoped_cleanup &)=delete
scoped_cleanup(scoped_cleanup &&other) noexcept
scoped_cleanup & operator=(const scoped_cleanup &)=delete
scoped_cleanup(FunT cleanup)
void disengage() noexcept
scoped_cleanup & operator=(scoped_cleanup &&other) noexcept