跳转至

base/include/base/scope_guard/scope_guard.hpp

Provides RAII-style scope guard for automatic cleanup. More...

Namespaces

Name
cf

Classes

Name
class cf::ScopeGuard
RAII scope guard for automatic cleanup operations.

Detailed Description

Provides RAII-style scope guard for automatic cleanup.

Author: Charliechen114514

Version: 0.1

Since: 0.1

Date: 2026-02-21

Implements a scope guard that executes a provided function upon destruction, ensuring cleanup operations are performed even when exceptions occur.

Source code

#pragma once
#include <functional>

namespace cf {

class ScopeGuard {
  public:
    template <typename F> explicit ScopeGuard(F&& f) : fn_(std::forward<F>(f)) {}

    ~ScopeGuard() noexcept(false) {
        if (active_)
            fn_();
    }

    ScopeGuard(const ScopeGuard&) = delete;

    ScopeGuard& operator=(const ScopeGuard&) = delete;

    ScopeGuard(ScopeGuard&&) = delete;

    ScopeGuard& operator=(ScopeGuard&&) = delete;

    void dismiss() noexcept { active_ = false; }

  private:
    std::function<void()> fn_;

    bool active_ = true;
};

} // namespace cf

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