上代码
/**
* from https://github.com/Microsoft/GSL
**/
template <class F>
class final_action
{
public:
static_assert(!std::is_reference<F>::value && !std::is_const<F>::value &&
!std::is_volatile<F>::value,
"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& operator=(const final_action&) = delete;
final_action& operator=(final_action&&) = delete;
~final_action() noexcept
{
if (invoke_) f_();
}
private:
F f_;
bool invoke_{true};
};
template <class F> final_action<typename std::remove_cv<typename std::remove_reference<F>::type>::type>
finally(F&& f) noexcept
{
return final_action<typename std::remove_cv<typename std::remove_reference<F>::type>::type>(
std::forward<F>(f));
}
调用
auto action = finally([this]{
//TODO
});
总结
这个模板是用了类的析构函数的方法,处理函数结束时,做的一些处理,跟QMutexLocker工作原理差不多的;分享在这,主要给自己当笔记了;估计也没有人能搜索到…
本文介绍了一个名为 final_action 的 C++ 模板类,该类利用析构函数来确保在对象生命周期结束时执行特定操作。类似于 QMutexLocker 的工作机制,此模板可以用于实现资源的自动管理和清理。
256

被折叠的 条评论
为什么被折叠?



