Abusing c++11 unique_ptr to execute code upon leaving the scope
c++, c++11, unique-ptr
Solution
Define a maker-function in some header for ease-of-use:
template<class F> auto scope_guard(F&& f) {
return std::unique_ptr<void, std::decay<F>::type>{(void*)1, std::forward<F>(f)};
}
And use it like:
auto unique = scope_guard([&](void*){/* cleanup here */});
Problem
I want to use `std::unique_ptr`'s deleter to guarantee some code will execute upon leaving the scope. For example let's say I have a class `Event` with function `set_event()`. I want to make sure that upon leaving the scope, the function `my_event.set_event()` will be called. I managed to get to something similar to this: ``` Event my_event; auto releasing_function = [&my_event] (void*){my_event.set_event();}; std::unique_ptr<void, decltype(releasing_function)> safe_event((void*)1, releasing_function); ``` But I feel like we can do better. Maybe a one liner without this auto lambda function, or avoiding this ugly `(void*)1`. Maybe even removing `unique_ptr` completely. Edit: I want to avoid utility classes. That's too easy :)