77 lines
2.4 KiB
C++
77 lines
2.4 KiB
C++
#pragma once
|
|
|
|
#include <memory>
|
|
#include <mutex>
|
|
#include <concepts>
|
|
#include <utility>
|
|
|
|
/**
|
|
* @brief C++26 Smart Singleton for DLL Hot-Reloading.
|
|
* Uses shared_ptr to ensure memory safety across thread boundaries
|
|
* during forceful destruction and DLL unloads.
|
|
*/
|
|
template <typename T>
|
|
class Singleton {
|
|
private:
|
|
// This "Token" trick allows std::shared_ptr to create the object
|
|
// even if T's constructor is private/protected.
|
|
struct ConstructorProxy : public T {
|
|
template<typename... Args>
|
|
ConstructorProxy(Args&&... args) : T(std::forward<Args>(args)...) {}
|
|
};
|
|
public:
|
|
// Delete copy/move
|
|
Singleton(const Singleton&) = delete;
|
|
Singleton& operator=(const Singleton&) = delete;
|
|
|
|
template <typename... Args>
|
|
static std::shared_ptr<T> init(Args&&... args) {
|
|
auto ptr = m_instance.load(std::memory_order_acquire);
|
|
if (ptr) return ptr;
|
|
|
|
std::lock_guard lock(m_lifecycle_mutex);
|
|
ptr = m_instance.load(std::memory_order_relaxed);
|
|
if (!ptr) {
|
|
// We wrap T in ConstructorProxy so 'new' works here,
|
|
// but the resulting shared_ptr is still shared_ptr<T>.
|
|
ptr = std::make_shared<ConstructorProxy>(std::forward<Args>(args)...);
|
|
m_instance.store(ptr, std::memory_order_release);
|
|
}
|
|
return ptr;
|
|
}
|
|
|
|
/**
|
|
* @brief Access the existing instance.
|
|
* @throws std::runtime_error if init() hasn't been called yet.
|
|
*/
|
|
static std::shared_ptr<T> getInstance() {
|
|
auto ptr = m_instance.load(std::memory_order_acquire);
|
|
if (!ptr) {
|
|
throw std::runtime_error("Singleton accessed via get() before init()!");
|
|
}
|
|
return ptr;
|
|
}
|
|
|
|
/**
|
|
* @brief Safe destruction for DLL unloading.
|
|
* Shared_ptr ensures that threads currently using the instance
|
|
* don't crash; the memory is freed only when the last reference drops.
|
|
*/
|
|
static void destroyInstance() {
|
|
std::lock_guard lock(m_lifecycle_mutex);
|
|
m_instance.store(nullptr, std::memory_order_release);
|
|
}
|
|
|
|
static bool isAlive() {
|
|
return m_instance.load(std::memory_order_acquire) != nullptr;
|
|
}
|
|
|
|
protected:
|
|
Singleton() = default;
|
|
virtual ~Singleton() = default;
|
|
|
|
private:
|
|
// atomic<shared_ptr> is a C++20 feature, perfect for C++26
|
|
static inline std::atomic<std::shared_ptr<T>> m_instance{nullptr};
|
|
static inline std::mutex m_lifecycle_mutex;
|
|
}; |