跳转至

base/include/base/helpers/once_init.hpp

Provides thread-safe lazy initialization utilities. More...

Namespaces

Name
cf

Classes

Name
struct cf::CallOnceInit
Thread-safe lazy initialization template.

Detailed Description

Provides thread-safe lazy initialization utilities.

Author: Charliechen114514

Version: 0.1

Since: 0.1

Date: 2026-02-21

Implements the CallOnceInit template for one-time resource initialization with thread safety and forced re-initialization support.

Source code

#pragma once
#include <mutex>
#include <utility>

namespace cf {

template <typename Resources> struct CallOnceInit {
  public:
    template <typename... Args> explicit CallOnceInit(Args&&... args)
        : resource(std::forward<Args>(args)...), initialized(true) {}

    CallOnceInit() = default;

    Resources& get_resources() {
        if (!initialized) {
            std::call_once(init_flag, [this]() {
                init_resources();
                initialized = true;
            });
        }
        return resource;
    }

    void force_reinit() {
        std::lock_guard<std::mutex> lock(force_mtx);
        force_do_reinit();
        initialized = true;
    }

    template <typename... Args> void force_reinit(Args&&... args) {
        std::lock_guard<std::mutex> lock(force_mtx);
        resource = Resources(std::forward<Args>(args)...);
        initialized = true;
    }

  protected:
    Resources resource;

    virtual bool init_resources() = 0;

    virtual bool force_do_reinit() = 0;

  private:
    std::once_flag init_flag;

    std::mutex force_mtx;

    bool initialized{false};
};

} // namespace cf

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