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

We have some resource that needs to be manually released. Other than explicitly writing a RAII wrapper to manage its resource, is there any built-in template or class in the std library to automatically execute a lambda task?

{
    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

      

The class might look like this, but I'm wondering if the wheel might already be embedded in the std library, or I should write my own.

struct GuardedTask
{
    std::function<void()> task;
    GuardedTask(std::function<void()> f): task(f) {}
    ~GuardedTask(){ task(); }
};

      

+3


source to share


2 answers


This pattern is called scope guard and has many other uses besides RAII flushing, such as transaction security features. Unfortunately, there is no standard protection measure , but there is a proposal P0052 that is intended to implement this.



+3


source


You can use a custom delete element on std::unique_ptr

.



Cf this question .

+2


source







All Articles