Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang-style "defer" in C++ [duplicate]

I was reading about the go language's defer statement. It allows you to specify an action to take when a function has ended. For example, if you have a file pointer or resource, instead of writing free/delete with every possible return path, you just need to specify the defer function once.

It looks like an analogue might be coming to C++ eventually (What is standard defer/finalizer implementation in C++?, Will there be standardization of scope guard/scope exit idioms?) Until then, is there anything unforeseen about doing it with an object whose destructor makes a callback? It looks like the destructor order for local variables is sane and that it also handles exceptions well, though maybe not exiting on signals.

Here is a sample implementation... is there anything troubling about it?

#include <iostream>
#include <functional>
using namespace std;

class FrameExitTask {
    std::function<void()> func_;
public:
    FrameExitTask(std::function<void()> func) :
    func_(func) {
    }
    ~FrameExitTask() {
        func_();
    }
    FrameExitTask& operator=(const FrameExitTask&) = delete;
    FrameExitTask(const FrameExitTask&) = delete;
};

int main() {
    FrameExitTask outer_task([](){cout << "world!";});
    FrameExitTask inner_task([](){cout << "Hello, ";});
    if (1+1 == 2)
        return -1;
    FrameExitTask skipped_task([](){cout << "Blam";});
}

Output: Hello, world!

like image 824
daveagp Avatar asked Oct 10 '15 05:10

daveagp


2 Answers

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?
like image 103
pepper_chico Avatar answered Oct 18 '22 06:10

pepper_chico


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.

like image 21
Nir Friedman Avatar answered Oct 18 '22 06:10

Nir Friedman