by toth · 10y ago · 0 comments
struct OnScopeExit {
OnScopeExit(std::function<void()> f) : f_(f) {};
~OnScopeExit() { f_();};
std::function<void()> f_;
};
Which you'd then use as {
OnScopeExit x([]() { std::cout << "Exited scope!" << std:endl; };
// ...
}in your OnScopeExit we could use templates (and not use std::function), that way any callable thing could be called - and it would be lighter than std::function
auto f = []() { std::cout << "Exited Scope!" << std::endl; };
OnScopeExit<decltype(f)> x(f);
The way unique_ptr does it is by using type erasure, which requires a virtual function call internally, just like std::function.That's shared_ptr. unique_ptr does not perform type erasure.
template<typename T>
struct OnScopeExit {
OnScopeExit(T f) : f_(f) {};
~OnScopeExit() { f_();};
T f_;
};
template<typename T>
OnScopeExit<T> make_scope_exit(T f) { return OnScopeExit<T>(f); }
And then you use it as auto x = make_scope_exit([]() { std::cout << "Exitced Scope!" << std::endl; });