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!";
    }};
}

Deferred guard creation

Using the NoCreate tag, it's possible to create an empty instance that's populated later by moving another object over it, for example to have a conditional guard:

Containers::ScopeGuard e{NoCreate};

/* Read from stdin if desired, otherwise scope-guard an opened file */
int fd;
if(filename == "-") {
    fd = STDIN_FILENO;
} else {
    fd = open(filename.data(), O_RDONLY);
    e = Containers::ScopeGuard{fd, close};
}

Constructors, destructors, conversion operators

template<class T, class Deleter>
ScopeGuard(T handle, Deleter deleter) explicit
Constructor.
template<class Deleter>
ScopeGuard(Deleter deleter) explicit
ScopeGuard(Corrade::NoCreateT) explicit noexcept new in Git master
Construct without creating a guard.
ScopeGuard(const ScopeGuard&) deleted
Copying is not allowed.
ScopeGuard(ScopeGuard&& other) noexcept new in Git master
Move constructor.
~ScopeGuard()
Destructor.

Public functions

auto operator=(const ScopeGuard&) -> ScopeGuard& deleted
Copying is not allowed.
auto operator=(ScopeGuard&&) -> ScopeGuard& noexcept new in Git master
Move assignment.
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(Corrade::NoCreateT) explicit noexcept new in Git master

Construct without creating a guard.

The constructed instance is equivalent to a moved-from state. Move another object over it to make it useful.

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. The instance is then equivalent to a moved-out state.