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