Corrade::Containers::ScopedExit class

Scoped exit.

Use it to call close/destroy/exit functions on pointer-like or integer-like object handles at the end of scope. Useful when you have many early returns and want to ensure the exit function gets called every time. Example:

{
    int fd = open("file.dat", O_RDONLY);
    Containers::ScopedExit e{fd, close};
} // fclose(f) gets called at the end of the scope

You can also specify a non-capturing lambda for more involved operations. Note that the handle is copied by value, so references won't work.

FILE* f{};

{
    f = fopen("file.dat", "r");
    Containers::ScopedExit e{&f, [](FILE** f) {
        fclose(*f);
        *f = nullptr;
    }};
}

// f is nullptr again

Constructors, destructors, conversion operators

template<class T, class Deleter>
ScopedExit(T handle, Deleter deleter) explicit
Constructor.
ScopedExit(const ScopedExit&) deleted
Copying is not allowed.
ScopedExit(ScopedExit&&) deleted
Moving is not allowed.
~ScopedExit()
Destructor.

Public functions

auto operator=(const ScopedExit&) -> ScopedExit& deleted
Copying is not allowed.
auto operator=(ScopedExit&&) -> ScopedExit& deleted
Moving is not allowed.
void release()
Release the handle ownership.

Function documentation

Corrade::Containers::ScopedExit::~ScopedExit()

Destructor.

Executes the deleter passed in constructor. Does nothing if release() has been called.

void Corrade::Containers::ScopedExit::release()

Release the handle ownership.

Causes the deleter passed in constructor to not get called on destruction.