by thrownaway2424 · 10y ago · 0 comments
std::unique_ptr<void> finally(42, [](void* unused){ whatever }); 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.
auto scope_guard = [](void*) { };
unique_ptr<void, decltype(scope_guard)> finally{nullptr, scope_guard};
This is not very idiomatic. Something like toth mentioned makes more sense. If you want it to be efficient, use this: template <class Fun>
class scope_guard {
scope_guard() = delete;
scope_guard(const scope_guard&) = delete;
scope_guard& operator=(const scope_guard&) = delete;
public:
scope_guard(Fun f) : fun_(std::move(f)) {}
~scope_guard() {
fun_();
}
private:
Fun fun_;
};
template <class Fun>
scope_guard<Fun> make_scope_guard(Fun f) {
return {std::move(f)};
}
auto guard = make_scope_guard([] { cleanup(); });
The difference is: there's no indirection through std::function, so you save yourself a (potential) heap allocation.It provides some macros to make it easier to use, e.g.
SCOPE_EXIT {
cleanup();
more_cleanup();
if (needs_even_more_cleanup)
even_more_cleanup();
};