From 6ef2d79a730b79e7cb075678f81b327637a3d29f Mon Sep 17 00:00:00 2001 From: Laurent Pinchart Date: Tue, 5 Aug 2025 02:31:50 +0300 Subject: [PATCH] libcamera: utils: Add scope_exit class MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The scope_exit class is an implementation of the identically named C++ library fundamentals TS v3 class, as documented in [1]. It is a simpler version of the libcamera-specific ScopeExitActions class and doesn't require dynamic heap memory allocation, making it more suitable for hot paths. The class is not documented as it implements a C++ standard (even if experimental) API. [1] https://en.cppreference.com/w/cpp/experimental/scope_exit/scope_exit.html Signed-off-by: Laurent Pinchart Reviewed-by: Barnabás Pőcze Reviewed-by: Stefan Klug Signed-off-by: Kieran Bingham --- include/libcamera/base/utils.h | 38 ++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/include/libcamera/base/utils.h b/include/libcamera/base/utils.h index 8d5c3578..f21c6dc0 100644 --- a/include/libcamera/base/utils.h +++ b/include/libcamera/base/utils.h @@ -21,6 +21,7 @@ #include #include +#include #include #ifndef __DOXYGEN__ @@ -428,6 +429,43 @@ private: std::vector> actions_; }; +#ifndef __DOXYGEN__ +template +class scope_exit +{ +public: + template>, scope_exit> && + std::is_constructible_v> * = nullptr> + explicit scope_exit(Fn &&fn) + : exitFunction_(std::forward(fn)) + { + static_assert(std::is_nothrow_constructible_v); + } + + ~scope_exit() + { + if (active_) + exitFunction_(); + } + + void release() + { + active_ = false; + } + +private: + LIBCAMERA_DISABLE_COPY_AND_MOVE(scope_exit) + + EF exitFunction_; + bool active_ = true; +}; + +template +scope_exit(EF) -> scope_exit; + +#endif /* __DOXYGEN__ */ + } /* namespace utils */ #ifndef __DOXYGEN__