本文介绍了golang样式的“ defer”在C ++中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在阅读有关Go语言的声明。它允许您指定函数结束后要执行的操作。例如,如果您有文件指针或资源,则无需为每个可能的返回路径编写自由/删除操作,而只需指定一次defer函数。

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.

它看起来类似物最终可能会进入C ++(,)在那之前,使用析构函数进行回调的对象进行此操作是否有不可预见的事情?看起来,并且

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";});
}

输出:你好,世界!

推荐答案

这已经存在,它被称为范围守护。观看以下精彩演讲:。这使您可以轻松创建要在退出时调用的任意可调用对象。这是较新的版本;它最初是在很久以前就开发出来的。

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.

我想一种语言可以尝试解决这个问题,但这很复杂。在C ++中,很少将抛出析构函数视为好主意。

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.

这篇关于golang样式的“ defer”在C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 02:58