mercredi 25 février 2015

Abusing c++11 unique_ptr to execute code upon leaving the scope

I want to use 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 event removing unique_ptr completely.


Edit: I want to avoid utility classes. That's too easy :)


Aucun commentaire:

Enregistrer un commentaire