Correctly implement finally block using C++ lambda

后端 未结 2 1396
隐瞒了意图╮
隐瞒了意图╮ 2021-01-30 22:33

I want to implement a finally block in my C++ program, and the language certainly has the tools to do it if not a native facility. I was wondering what the best way

2条回答
  •  一整个雨季
    2021-01-30 23:13

    An alternative solution using std::function. No factory function needed. No per-use template instantiation (better footprint?!). No std::move and && stuff needed, no auto needed ;)

    class finally
    {
        std::function m_finalizer;
        finally() = delete;
    
    public:
        finally( const finally& other ) = delete;
        finally( std::function finalizer )
         : m_finalizer(finalizer)
        {
        }
        ~finally()
        {
            std::cout << "invoking finalizer code" << std::endl;
        if( m_finalizer )
            m_finalizer();
        }
    };
    

    Usage:

    int main( int argc, char * argv[] )
    {
        bool something = false;
        try
        {
        try
        {
                std::cout << "starting" << std::endl;
            finally final([&something]() { something = true; });
            std::cout << "throwing" << std::endl;
            throw std::runtime_error("boom");
        }
        catch(std::exception & ex )
        {
            std::cout << "inner catch" << std::endl;
            throw;
        }
        }
        catch( std::exception & ex )
        {
        std::cout << "outer catch" << std::endl;
            if( something )
        {
            std::cout << "works!" << std::endl;
            }
            else
        {
            std::cout << "NOT working!" << std::endl;
            }
        }
        std::cout << "exiting" << std::endl;
        return 0;
    }
    

    Output:

    starting

    throwing

    invoking finalizer code

    inner catch

    outer catch

    works!

    exiting

提交回复
热议问题