c++boostgostlraii

What is standard defer/finalizer implementation in C++?


General idea of Golang-style defer is explained here and here.

I wonder, does STL (of C++11, C++14, ...) or maybe Boost or maybe some other library contain implementation of such a class? So I could just use it without reimplementing it in every new project.


Solution

  • There is a proposal for std::unique_resource_t which will enable code like

    auto file=make_unique_resource(::fopen(filename.c_str(),"w"),&::fclose);
    

    for resources, and it defines a general scope_exit, which should be the same as defer:

    // Always say goodbye before returning,
    auto goodbye = make_scope_exit([&out]() ->void
    {
    out << "Goodbye world..." << std::endl;
    });
    

    It will be considered for likely adoption in the Post-C++17 standard.