Aleksander Alekseev Aleksander Alekseev - 4 months ago 17
C++ Question

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.

Answer

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 looks like it will be part of the next standard.

Comments