golang-style "defer" in C++
Boost discuss this in Smart Pointer Programming Techniques:
- http://www.boost.org/doc/libs/1_59_0/libs/smart_ptr/sp_techniques.html#handle
You can do, for example:
#include <memory>
#include <iostream>
#include <functional>
using namespace std;
using defer = shared_ptr<void>;
int main() {
defer _(nullptr, bind([]{ cout << ", World!"; }));
cout << "Hello";
}
Or, without bind
:
#include <memory>
#include <iostream>
using namespace std;
using defer = shared_ptr<void>;
int main() {
defer _(nullptr, [](...){ cout << ", World!"; });
cout << "Hello";
}
You may also as well rollout your own small class for such, or make use of the reference implementation for N3830/P0052:
- N3830: https://github.com/alsliahona/N3830
- P0052: https://github.com/PeterSommerlad/scope17
The C++ Core Guidelines also have a guideline which employs the gsl::finally
function, for which there's an implementation here.
There are many codebases that employ similar solutions for this, hence, there's a demand for this tool.
Related SO discussion:
- Is there a proper 'ownership-in-a-package' for 'handles' available?
- Where's the proper (resource handling) Rule of Zero?
This already exists, and it's called scope guard. See this fantastic talk: https://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2012-Andrei-Alexandrescu-Systematic-Error-Handling-in-C. This lets you easily create an arbitrary callable to be called at exit. This is the newer version; it was developed originally long before go existed.
It works perfectly in general, but I'm not sure what you mean by it handling exceptions. Throwing exceptions from a function that has to be called at scope exit is a mess. The reason: when an exception is thrown (and not immediately caught), current scope exits. All destructors get run, and the exception will continue propagating. If one of the destructors throws, what do you do? You now have two live exceptions.
I suppose there are ways a language could try to deal with this, but it's very complex. In C++, it's very rare that a throwing destructor would be considered a good idea.