跳转至

cf::ScopeGuard

RAII scope guard for automatic cleanup operations. More...

#include <scope_guard.hpp>

Public Functions

Name
template <typenameF >
ScopeGuard(F && f)
Constructs a scope guard with a cleanup function.
~ScopeGuard()
Destroys the scope guard and executes the cleanup function.
ScopeGuard(constScopeGuard & ) =delete
Copy constructor is deleted.
ScopeGuard & operator=(constScopeGuard & ) =delete
Copy assignment operator is deleted.
ScopeGuard(ScopeGuard && ) =delete
Move constructor is deleted.
ScopeGuard & operator=(ScopeGuard && ) =delete
Move assignment operator is deleted.
void dismiss()
Dismisses the scope guard.

Detailed Description

class cf::ScopeGuard;

RAII scope guard for automatic cleanup operations.

Note: The guard is not movable or copyable. This design ensures cleanup operations are executed exactly once.

Warning: The stored function is invoked during destruction. Any exceptions thrown by the function propagate during stack unwinding.

Executes a provided function upon destruction unless explicitly dismissed. Useful for ensuring resources are released or cleanup operations are performed when leaving a scope.

{
    FILE* f = fopen("data.txt", "r");
    cf::ScopeGuard guard([&f]() { fclose(f); });

    // Use the file...
    // File is closed automatically when leaving scope.
}

Public Functions Documentation

function ScopeGuard

template <typenameF >
inline explicit ScopeGuard(
    F && f
)

Constructs a scope guard with a cleanup function.

Parameters:

  • f Function to execute on destruction. Must be callable with no arguments.

Exceptions:

  • May throw if function copy/move constructor throws.

Since: 0.1

Note: None.

Warning: None.

function ~ScopeGuard

inline ~ScopeGuard()

Destroys the scope guard and executes the cleanup function.

Exceptions:

  • May propagate exceptions thrown by the cleanup function.

Since: 0.1

Note: None.

Warning: Any exceptions thrown by the cleanup function propagate during stack unwinding.

The cleanup function is executed only if the guard has not been dismissed.

function ScopeGuard

ScopeGuard(
    constScopeGuard & 
) =delete

Copy constructor is deleted.

Since: 0.1

function operator=

ScopeGuard & operator=(
    constScopeGuard & 
) =delete

Copy assignment operator is deleted.

Since: 0.1

function ScopeGuard

ScopeGuard(
    ScopeGuard && 
) =delete

Move constructor is deleted.

Since: 0.1

function operator=

ScopeGuard & operator=(
    ScopeGuard && 
) =delete

Move assignment operator is deleted.

Since: 0.1

function dismiss

inline void dismiss()

Dismisses the scope guard.

Exceptions:

  • None.

Since: 0.1

Note: Once dismissed, the cleanup function cannot be re-activated.

Warning: None.

Prevents the cleanup function from being executed upon destruction. Irreversible once called.


Updated on 2026-03-09 at 10:14:00 +0000