Skip to content

Commit

Permalink
fixup! src: do not use std::function for OnScopeLeave
Browse files Browse the repository at this point in the history
  • Loading branch information
addaleax committed Nov 6, 2019
1 parent 776285f commit e3aa3b6
Showing 1 changed file with 17 additions and 1 deletion.
18 changes: 17 additions & 1 deletion src/util.h
Original file line number Diff line number Diff line change
Expand Up @@ -503,7 +503,23 @@ template <typename T> inline void USE(T&&) {}
template <typename Fn>
struct OnScopeLeaveImpl {
Fn fn_;
~OnScopeLeaveImpl() { fn_(); }
bool active_;

explicit OnScopeLeaveImpl(Fn&& fn) : fn_(std::move(fn)), active_(true) {}
~OnScopeLeaveImpl() { if (active_) fn_(); }

OnScopeLeaveImpl(const OnScopeLeaveImpl& other) = delete;
OnScopeLeaveImpl& operator=(const OnScopeLeaveImpl& other) = delete;
OnScopeLeaveImpl(OnScopeLeaveImpl&& other)
: fn_(std::move(other.fn_)), active_(other.active_) {
other.active_ = false;
}
OnScopeLeaveImpl& operator=(OnScopeLeaveImpl&& other) {
if (this == &other) return *this;
this->~OnScopeLeave();
new (this)OnScopeLeaveImpl(std::move(other));
return *this;
}
};

// Run a function when exiting the current scope. Used like this:
Expand Down

0 comments on commit e3aa3b6

Please sign in to comment.