golang-style “defer” in C++ [duplicate]

落爺英雄遲暮 提交于 2020-02-01 01:38:46

问题


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!


回答1:


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.




回答2:


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?



回答3:


This already exists in C++, and it's a tremendously bad idea and the example you gave exemplifies why it's a pointless thing to do and I hope that the Committee never introduces it.

For example, if you have a file handle, then write a class to do it for you and then you won't have to write a defer statement for every single use case, which you could easily forget to do. Or just plain get it wrong. You write one destructor, once. That's it. Then you're guaranteed for all uses of the class that it's safe. It's much safer and much easier.



来源:https://stackoverflow.com/questions/33050620/golang-style-defer-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!