From 9b3bcee71d55b731ae88c8d285c566b58423738e Mon Sep 17 00:00:00 2001 From: David Snopek Date: Wed, 31 Jan 2024 14:39:24 -0600 Subject: [PATCH] Avoid creating objects that Godot is going to use placement new to initialize --- include/godot_cpp/core/memory.hpp | 19 +++++++++++++++++++ src/variant/variant.cpp | 12 ++++++------ 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/include/godot_cpp/core/memory.hpp b/include/godot_cpp/core/memory.hpp index 97a2b13b..0d3b8b9c 100644 --- a/include/godot_cpp/core/memory.hpp +++ b/include/godot_cpp/core/memory.hpp @@ -190,6 +190,25 @@ struct _GlobalNilClass { static _GlobalNil _nil; }; +template +class UninitializedValue { + typename std::aligned_storage::type data; + +public: + UninitializedValue() {} + + UninitializedValue(const UninitializedValue &) = delete; + UninitializedValue &operator=(const UninitializedValue &) = delete; + + T &get() { + return *reinterpret_cast(&data); + } + + T *ptr() { + return reinterpret_cast(&data); + } +}; + } // namespace godot #endif // GODOT_MEMORY_HPP diff --git a/src/variant/variant.cpp b/src/variant/variant.cpp index 945d6f40..b8336e3c 100644 --- a/src/variant/variant.cpp +++ b/src/variant/variant.cpp @@ -459,15 +459,15 @@ Variant::operator Signal() const { } Variant::operator Dictionary() const { - Dictionary result; - to_type_constructor[DICTIONARY](result._native_ptr(), _native_ptr()); - return result; + UninitializedValue result; + to_type_constructor[DICTIONARY](result.ptr(), _native_ptr()); + return result.get(); } Variant::operator Array() const { - Array result; - to_type_constructor[ARRAY](result._native_ptr(), _native_ptr()); - return result; + UninitializedValue result; + to_type_constructor[ARRAY](result.ptr(), _native_ptr()); + return result.get(); } Variant::operator PackedByteArray() const {