Corrade::Containers::ScopeGuard class

Scope guard.

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::ScopeGuard 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::ScopeGuard e{&f, [](FILE** f) {
        fclose(*f);
        *f = nullptr;
    }};
}

// f is nullptr again

For calling global functions with no extra state, the constructor can also take just a parameter-less function or lambda:

{
    Containers::ScopeGuard e{[]() {
        Utility::Debug{} << "We're done here!";
    }};
}

Constructors, destructors, conversion operators

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

Public functions

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

Function documentation

template<class Deleter>
Corrade::Containers::ScopeGuard::ScopeGuard(Deleter deleter) explicit

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Corrade::Containers::ScopeGuard::~ScopeGuard()

Destructor.

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

void Corrade::Containers::ScopeGuard::release()

Release the handle ownership.

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