From 93af096d68fdcd6720c3e9e78689fb36a939ec4f Mon Sep 17 00:00:00 2001 From: Riyyi Date: Wed, 21 Sep 2022 23:20:19 +0200 Subject: [PATCH] Util: Set singleton instance pointer early --- src/ruc/singleton.h | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/ruc/singleton.h b/src/ruc/singleton.h index bfcce48..c753dc0 100644 --- a/src/ruc/singleton.h +++ b/src/ruc/singleton.h @@ -6,7 +6,9 @@ #pragma once -#include +#include // malloc + +#include "meta/assert.h" namespace ruc { @@ -16,7 +18,10 @@ public: static inline T& the() { if (s_instance == nullptr) { - s_instance = new T { s {} }; + // Allocate memory for this instance + s_instance = static_cast(malloc(sizeof(T))); + // Call the constructor using placement new + new (s_instance) T { s {} }; } return *s_instance; @@ -24,10 +29,9 @@ public: static inline void destroy() { - if (s_instance) { - delete s_instance; - } + VERIFY(s_instance, "singleton does not exist"); + delete s_instance; s_instance = nullptr; }