3 ms·
I actually don't think there's a nice way of doing this without making the interface slightly more annoying. If you make OnScopeExit a template on a callable, t
by toth 10y ago
I actually don't think there's a nice way of doing this without making the interface slightly more annoying.
If you make OnScopeExit a template on a callable, then you need to give it the type of the callable explicitly on construction, which means that using a lambda becomes more annoying. I.e., you'd have to do it like this:
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.
- Kristine1975 10y ago>The way unique_ptr does it is by using type erasure, which requires a virtual function call internally That's shared_ptr. unique_ptr does not perform type erasure.
- deleted 10y ago[deleted]
- bennofs 10y agoCouldn't you do something like `auto x = make_on_scope_exit([]() { ... });`?
- toth 10y agoYes, you are right, I am wrong! That works just fine. For the record: 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; });
- corysama 10y agoAlexandrescu at CPPCon2015 describes how he does ScopeExit starting at 18 minutes into this video http://youtu.be/WjTrfoiB0MQ http://youtu.be/WjTrfoiB0MQ
- kzhahou 10y agoWith all due respect to Alexandrescu's incredible C++ skills, I find that his style of programming is very detrimental to the overall quality of the C++ environment. C++ is a very abusable language. This is reflected both in its capabilities and in the ability to shoot yourself in the foot. These points are obviously well-covered in any C++ discussion. Now, Alexandrescu brings a style of programming in which you exploit templates, sometimes macros, operator overloading, and everything else, in order to squeeze out more generality/reusability out of a piece of code, or simplify the coder-visible syntax of some construct. We see that right here: the above comments show a few ways to run arbitrary code on a scope exit. Each of the examples above is perfectly easy to follow along. But then the YouTube video show's Alexandrescu's take, and it's a real brain-warper. He invokes a couple of levels of C++ trickery to get his effect. Now, his end result is wonderful... but it's also not easily understandable. If you write code in his style at your job, good luck to the person that takes over your code after you leave the project. They'll have a hell of a time. IMHO a developer should always sacrifice syntactic sugar, with no performance penalty if done correctly, in exchange for more understandable code.
- pklausler 10y agoYou can omit the "auto x =", too.