std 库中是否有类/模板可以在超出范围时执行任务

Is there a class/template in std library to perform a task when out of scope?

本文关键字:范围 执行任务 是否 std      更新时间:2023-10-16

我们有一些资源,需要手动释放。除了显式编写用于管理其资源的 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上使用自定义删除器。

参考这个问题。