mirror of
https://github.com/KartKrewDev/RingRacers.git
synced 2025-10-30 08:01:28 +00:00
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:
parent
15acefcc33
commit
51e0bed20a
1 changed files with 37 additions and 0 deletions
37
src/cxxutil.hpp
Normal file
37
src/cxxutil.hpp
Normal 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__
|
||||||
Loading…
Add table
Reference in a new issue