UDocumentation UE5.7 10.02.2026 (Source)
API documentation for Unreal Engine 5.7
LazySingleton.h
Go to the documentation of this file.
1// Copyright Epic Games, Inc. All Rights Reserved.
2
3#pragma once
4
6
9{
10protected:
11 template<class T> static void Construct(void* Place) { ::new (Place) T; }
12 template<class T> static void Destruct(T* Instance) { Instance->~T(); }
13};
14
49template<class T>
50class TLazySingleton final : public FLazySingleton
51{
52public:
58 static T& Get()
59 {
60 return GetLazy(Construct<T>).GetValue();
61 }
62
64 static void TearDown()
65 {
66 return GetLazy(nullptr).Reset();
67 }
68
70 static T* TryGet()
71 {
72 return GetLazy(Construct<T>).TryGetValue();
73 }
74
75private:
76 static TLazySingleton& GetLazy(void(*Constructor)(void*))
77 {
78 static TLazySingleton Singleton(Constructor);
79 return Singleton;
80 }
81
82 alignas(T) unsigned char Data[sizeof(T)];
83 T* Ptr;
84
85 TLazySingleton(void(*Constructor)(void*))
86 {
87 if (Constructor)
88 {
89 Constructor(Data);
90 }
91
92 Ptr = Constructor ? (T*)Data : nullptr;
93 }
94
95#if (!defined(DISABLE_LAZY_SINGLETON_DESTRUCTION) || !DISABLE_LAZY_SINGLETON_DESTRUCTION)
97 {
98 Reset();
99 }
100#endif
101
102 T* TryGetValue()
103 {
104 return Ptr;
105 }
106
107 T& GetValue()
108 {
109 check(Ptr);
110 return *Ptr;
111 }
112
113 void Reset()
114 {
115 if (Ptr)
116 {
117 Destruct(Ptr);
118 Ptr = nullptr;
119 }
120 }
121};
#define check(expr)
Definition AssertionMacros.h:314
UE_FORCEINLINE_HINT TSharedRef< CastToType, Mode > StaticCastSharedRef(TSharedRef< CastFromType, Mode > const &InSharedRef)
Definition SharedPointer.h:127
Definition LazySingleton.h:9
static void Destruct(T *Instance)
Definition LazySingleton.h:12
static void Construct(void *Place)
Definition LazySingleton.h:11
Definition LazySingleton.h:51
static void TearDown()
Definition LazySingleton.h:64
static T & Get()
Definition LazySingleton.h:58
static T * TryGet()
Definition LazySingleton.h:70