From 51e0bed20ad915401898306d409ff29b7e8015ad Mon Sep 17 00:00:00 2001 From: Eidolon Date: Mon, 12 Dec 2022 16:40:56 -0600 Subject: [PATCH] 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. --- src/cxxutil.hpp | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/cxxutil.hpp diff --git a/src/cxxutil.hpp b/src/cxxutil.hpp new file mode 100644 index 000000000..befe9c20b --- /dev/null +++ b/src/cxxutil.hpp @@ -0,0 +1,37 @@ +#ifndef __SRB2_CXXUTIL_HPP__ +#define __SRB2_CXXUTIL_HPP__ + +#include +#include + +namespace srb2 { + +template +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 +Finally> finally(F&& f) noexcept { + return Finally {std::forward(f)}; +} + +} + +#endif // __SRB2_CXXUTIL_HPP__