Clean up final_act and finally, closes #752 and #846

This commit is contained in:
Herb Sutter 2021-02-24 15:51:29 -08:00
parent ef0ffefe52
commit 4cd8873d3e

View File

@ -52,40 +52,21 @@ template <class F>
class final_action class final_action
{ {
public: public:
static_assert(!std::is_reference<F>::value && !std::is_const<F>::value && explicit final_action(F f) : f_(std::move(f)) { }
!std::is_volatile<F>::value, ~final_action() noexcept { f_(); }
"Final_action should store its callable by value");
explicit final_action(F f) noexcept : f_(std::move(f)) {}
final_action(final_action&& other) noexcept
: f_(std::move(other.f_)), invoke_(std::exchange(other.invoke_, false))
{}
final_action(const final_action&) = delete; final_action(const final_action&) = delete;
final_action& operator=(const final_action&) = delete; final_action& operator=(const final_action&) = delete;
final_action& operator=(final_action&&) = delete;
// clang-format off
GSL_SUPPRESS(f.6) // NO-FORMAT: attribute // terminate if throws
// clang-format on
~final_action() noexcept
{
if (invoke_) f_();
}
private: private:
F f_; F f_;
bool invoke_{true};
}; };
// finally() - convenience function to generate a final_action // finally() - convenience function to generate a final_action
template <class F> template <class F>
GSL_NODISCARD final_action<typename std::remove_cv<typename std::remove_reference<F>::type>::type> auto finally(F f) noexcept
finally(F&& f) noexcept
{ {
return final_action<typename std::remove_cv<typename std::remove_reference<F>::type>::type>( return final_action<F>{f};
std::forward<F>(f));
} }
// narrow_cast(): a searchable way to do narrowing casts of values // narrow_cast(): a searchable way to do narrowing casts of values