c++: add finally RAII utility

This mirrors the `finally` utility in Guidelines Support Library for
ensuring that a cleanup function is always called when the utility
object leaves scope, even when unwinding the stack from an exception.
This is to aid in transitioning malloc/free pairs in function bodies to
be more exception-safe.
This commit is contained in:
Eidolon 2022-12-12 16:40:56 -06:00
parent 15acefcc33
commit 51e0bed20a

37
src/cxxutil.hpp Normal file
View file

@ -0,0 +1,37 @@
#ifndef __SRB2_CXXUTIL_HPP__
#define __SRB2_CXXUTIL_HPP__
#include <type_traits>
#include <utility>
namespace srb2 {
template <class F>
class Finally {
public:
explicit Finally(const F& f) noexcept : f_(f) {}
explicit Finally(F&& f) noexcept : f_(f) {}
Finally(Finally&& from) noexcept : f_(std::move(from.f_)), call_(std::exchange(from.call_, false)) {}
Finally(const Finally& from) = delete;
void operator=(const Finally& from) = delete;
void operator=(Finally&& from) = delete;
~Finally() noexcept {
f_();
}
private:
F f_;
bool call_ = true;
};
template <class F>
Finally<std::decay_t<F>> finally(F&& f) noexcept {
return Finally {std::forward<F>(f)};
}
}
#endif // __SRB2_CXXUTIL_HPP__