Botan 3.13.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
31
32 scoped_cleanup(scoped_cleanup&& other) noexcept : m_cleanup(std::move(other.m_cleanup)) { other.disengage(); }
33
35 if(m_cleanup.has_value()) {
36 (*m_cleanup)(); // NOLINT(bugprone-exception-escape) clang-tidy bug
37 }
38 }
39
40 /**
41 * Disengage the cleanup callback, i.e., prevent it from being called
42 */
43 void disengage() noexcept { m_cleanup.reset(); }
44
45 private:
46 std::optional<FunT> m_cleanup;
47};
48
49} // namespace Botan
50
51#endif
scoped_cleanup & operator=(scoped_cleanup &&other)=delete
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