std 库中是否有类/模板可以在超出范围时执行任务
Is there a class/template in std library to perform a task when out of scope?
我们有一些资源,需要手动释放。除了显式编写用于管理其资源的 RAII 包装器外,std 库中是否有任何内置模板或类可以自动执行 lambda 任务?
{
auto resource = InitResource();
GuardedTask task ([&resource]{ FreeUp(resource); }); // Simply bind a clean up lambda
...
if(failed_condition_met) { return false; } // Free up
...
if(another_failed_condition_met) { return false; } // Free up
} // Free up
该类的行为可能如下所示,但我想知道 wheel 可能已经在 std 库中构建,或者我应该编写自己的轮子。
struct GuardedTask
{
std::function<void()> task;
GuardedTask(std::function<void()> f): task(f) {}
~GuardedTask(){ task(); }
};
此模式称为作用域防护,除 RAII 清理外还有许多其他用途,例如事务安全功能。不幸的是,没有标准化的范围保护,但有提案P0052旨在实现这一点。
您可以在std::unique_ptr
上使用自定义删除器。
参考这个问题。
相关文章:
- 是否可以依赖函数范围的静态变量来执行程序关闭期间调用的方法?
- 如何创建线程序列以按照启动顺序执行任务?
- 编写一个读取五个整数并执行一些任务的C++程序
- 命令模式 - 使用"weight"执行任务的命令
- OpenMP 4.5 任务依赖关系和执行顺序
- 如何在 Linux 上强制执行矢量下标超出范围的调试断言
- 使用 UWP 中的 IAsyncOperation 继续执行任务
- 独立子任务执行
- 在iOS设备上执行并发任务时如何设置正确的线程数?
- 函数返回本地变量,尽管变量不超出范围,没有编译器问题,并且代码执行
- 如何在执行异步后台任务的C++中构造对象
- 如何为基类构造函数中的每个子类执行特定任务
- std 库中是否有类/模板可以在超出范围时执行任务
- 正在执行 omp 任务的线程数
- 对相关数据执行任务级并行性
- 如何用c++在Windows主循环中执行任务
- 在析构函数中执行任务
- 线程在QT中执行任务时如何使用GUI
- 如何在Windows系统中以管理员身份透明地执行任务
- 如何告诉c++并发运行时重用前一个线程来执行任务