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?