scoped_guard.h (1167B)
1 // SPDX-FileCopyrightText: 2019-2022 Connor McLaughlin <stenzek@gmail.com> 2 // SPDX-License-Identifier: (GPL-3.0 OR CC-BY-NC-ND-4.0) 3 4 #pragma once 5 #include "types.h" 6 #include <optional> 7 #include <utility> 8 9 /// ScopedGuard provides an object which runs a function (usually a lambda) when 10 /// it goes out of scope. This can be useful for releasing resources or handles 11 /// which do not normally have C++ types to automatically release. 12 template<typename T> 13 class ScopedGuard final 14 { 15 public: 16 ALWAYS_INLINE ScopedGuard(T&& func) : m_func(std::forward<T>(func)) {} 17 ALWAYS_INLINE ScopedGuard(ScopedGuard&& other) : m_func(std::move(other.m_func)) { other.m_func = nullptr; } 18 19 ALWAYS_INLINE ~ScopedGuard() { Run(); } 20 21 ScopedGuard(const ScopedGuard&) = delete; 22 void operator=(const ScopedGuard&) = delete; 23 24 /// Runs the destructor function now instead of when we go out of scope. 25 ALWAYS_INLINE void Run() 26 { 27 if (!m_func.has_value()) 28 return; 29 30 m_func.value()(); 31 m_func.reset(); 32 } 33 34 /// Prevents the function from being invoked when we go out of scope. 35 ALWAYS_INLINE void Cancel() { m_func.reset(); } 36 37 private: 38 std::optional<T> m_func; 39 };