【问题标题】:Running a routine when a function returns or goes out of routine scope?当函数返回或超出例程范围时运行例程?
【发布时间】:2015-07-30 22:55:32
【问题描述】:

在 C++ 中,当函数返回或作用域例程超出范围时,是否有一种自动运行某些例程的好方法?

使用 goto 语句似乎有帮助,但是当抛出异常并且未由 catch 或 finally 语句处理时,它会丢失。不幸的是,finally 语句不能在 C++ 中使用。 RAII 是另一种实现方式,但它迫使我每次都定义一个类,这比 finally 语句更麻烦。

【问题讨论】:

标签: c++ exception-handling


【解决方案1】:

如果您使用的是 c++/11,则始终可以创建一个通用的、可重用的类,该类在其析构函数中运行任何函数。

#include <iostream>
#include <functional>

class RAIIPattern final
{
public:
    typedef std::function<void()> Func_t;

    RAIIPattern(Func_t onExitScope) : m_onExitScope(onExitScope) { }

    ~RAIIPattern() {
        if (m_onExitScope) m_onExitScope();
    }

private:
    // No copy
    RAIIPattern(const RAIIPattern&);
    RAIIPattern& operator=(const RAIIPattern&);

    Func_t m_onExitScope; 
};

int main ()
{
    using namespace std;
    RAIIPattern onExit([] { cout << "on exit 1" << endl; });

    {
        RAIIPattern onExit([] { cout << "on exit 2" << endl; });
    }

    return 0;
}

【讨论】:

    【解决方案2】:

    RAII 是另一种方式,但它迫使我定义一个类 每次都比finally语句麻烦。

    您可以使用Boost.ScopeExit

    或者使用std::function 或 lambdas 编写您自己的通用解决方案。基本思路如下:

    #include <iostream>
    
    template <class Function>
    class ScopeExit final
    {
    private:
        Function function;
    public:
        ScopeExit(Function function) : function(function) {}
        ~ScopeExit() { function(); }
    
        ScopeExit(ScopeExit const&) = delete;
        ScopeExit &operator=(ScopeExit const&) = delete;
    };
    
    template <class Function>
    ScopeExit<Function> MakeScopeExit(Function function)
    {
        return ScopeExit<Function>(function);
    }
    
    int main()
    {
        auto scope_exit = MakeScopeExit([]() { std::cout << "exit\n"; });
    
        std::cout << "function body\n";
    }
    

    【讨论】:

      猜你喜欢
      • 2018-03-26
      • 1970-01-01
      • 2015-12-18
      • 1970-01-01
      • 1970-01-01
      • 2016-06-11
      • 2016-11-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多