#pragma once #include #include #include #include /** * @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 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 ConstructorProxy(Args &&...args) : T(std::forward(args)...) { } }; public: // Delete copy/move Singleton(const Singleton &) = delete; Singleton &operator=(const Singleton &) = delete; template static std::shared_ptr 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. ptr = std::make_shared( std::forward(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 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 is a C++20 feature, perfect for C++26 static inline std::atomic> m_instance{nullptr}; static inline std::mutex m_lifecycle_mutex; };