UDocumentation UE5.7 10.02.2026 (Source)
API documentation for Unreal Engine 5.7
VVMLazyInitialized.h
Go to the documentation of this file.
1// Copyright Epic Games, Inc. All Rights Reserved.
2
3#pragma once
4
5#if WITH_VERSE_VM || defined(__INTELLISENSE__)
6
7#include "Containers/Array.h"
8#include "HAL/Platform.h"
9#include "VVMLog.h"
10#include <atomic>
11
12namespace Verse
13{
14
16
17// Acts like a smart pointer to T, meant to be used in global context, that:
18//
19// - Lazily initializes itself. It's only when you first touch it that anything happens.
20// - Never destroys itself.
21// - Is thread-safe. It's fine if you race on initialization.
22// - Doesn't do any fences or atomic ops in steady state.
23// - Has a leak "by design" - if there is a race on initialization, then there will be a leak.
24//
25// Basically, if N threads race on initialization, then you might allocate N versions of T but only one will win,
26// and the others will be allowed to leak. Since this will Never Happen (TM), it's fine.
27template <typename T>
29{
30 TLazyInitialized() = default;
31
32 T& Get()
33 {
34 T* Result = Data.load(std::memory_order_relaxed);
35 std::atomic_signal_fence(std::memory_order_seq_cst);
36 if (Result)
37 {
38 return *Result;
39 }
40 else
41 {
42 return GetSlow();
43 }
44 }
45
46 T& operator*()
47 {
48 return Get();
49 }
50
51 T* operator->()
52 {
53 return &Get();
54 }
55
56 const T& Get() const
57 {
58 return const_cast<TLazyInitialized*>(this)->Get();
59 }
60
61 const T& operator*() const
62 {
63 return Get();
64 }
65
66 const T* operator->() const
67 {
68 return &Get();
69 }
70
71private:
73 {
74 T* Object = new T();
75 T* Expected = nullptr;
76 Data.compare_exchange_strong(Expected, Object);
77 T* Result;
78 if (Expected)
79 {
81 Result = Expected;
82 }
83 else
84 {
85 Result = Object;
86 }
87 V_DIE_UNLESS(Data.load() == Result);
88 return *Result;
89 }
90
91 std::atomic<T*> Data = nullptr;
92};
93
94} // namespace Verse
95#endif // WITH_VERSE_VM
#define FORCENOINLINE
Definition AndroidPlatform.h:142
UE_FORCEINLINE_HINT FLinearColor operator*(float Scalar, const FLinearColor &Color)
Definition Color.h:473
UE_FORCEINLINE_HINT TSharedRef< CastToType, Mode > StaticCastSharedRef(TSharedRef< CastFromType, Mode > const &InSharedRef)
Definition SharedPointer.h:127
GeometryCollection::Facades::FMuscleActivationData Data
Definition MuscleActivationConstraints.h:15
FORCEINLINE T * Get(const FObjectPtr &ObjectPtr)
Definition ObjectPtr.h:426
UE_STRING_CLASS Result(Forward< LhsType >(Lhs), RhsLen)
Definition String.cpp.inl:732
Definition Archive.h:36