libcamera: utils: Add scope_exit class

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 <laurent.pinchart@ideasonboard.com>
Reviewed-by: Barnabás Pőcze <barnabas.pocze@ideasonboard.com>
Reviewed-by: Stefan Klug <stefan.klug@ideasonboard.com>
Signed-off-by: Kieran Bingham <kieran.bingham@ideasonboard.com>
This commit is contained in:
Laurent Pinchart
2025-08-05 02:31:50 +03:00
committed by Kieran Bingham
parent b37e69d434
commit 6ef2d79a73

View File

@@ -21,6 +21,7 @@
#include <utility>
#include <vector>
#include <libcamera/base/class.h>
#include <libcamera/base/private.h>
#ifndef __DOXYGEN__
@@ -428,6 +429,43 @@ private:
std::vector<std::function<void()>> actions_;
};
#ifndef __DOXYGEN__
template<typename EF>
class scope_exit
{
public:
template<typename Fn,
std::enable_if_t<!std::is_same_v<std::remove_cv_t<std::remove_reference_t<Fn>>, scope_exit> &&
std::is_constructible_v<EF, Fn>> * = nullptr>
explicit scope_exit(Fn &&fn)
: exitFunction_(std::forward<Fn>(fn))
{
static_assert(std::is_nothrow_constructible_v<EF, Fn>);
}
~scope_exit()
{
if (active_)
exitFunction_();
}
void release()
{
active_ = false;
}
private:
LIBCAMERA_DISABLE_COPY_AND_MOVE(scope_exit)
EF exitFunction_;
bool active_ = true;
};
template<typename EF>
scope_exit(EF) -> scope_exit<EF>;
#endif /* __DOXYGEN__ */
} /* namespace utils */
#ifndef __DOXYGEN__