5 ms·
I understand that your point is that unique_ptr facilitates resource management. But the example you provide is a misleading. How is this supposed to compile? T
by mavam 10y ago
I understand that your point is that unique_ptr facilitates resource management. But the example you provide is a misleading. How is this supposed to compile? The deleter type is part of the unique_ptr. So you need something along these lines:
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.
- thrownaway2424 10y agoYeah, again I am lazy and did not want to do all that typing on my phone. See https://godbolt.org/g/ywU2en https://godbolt.org/g/ywU2en for the full monty.
- Kristine1975 10y agoFacebook's Folly library implements something similar: https://github.com/facebook/folly/blob/master/folly/ScopeGuard.h https://github.com/facebook/folly/blob/master/folly/ScopeGua... 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(); };