From e7b8c4f0fcd72191e88d1c17abf5da08fe3a9c6f Mon Sep 17 00:00:00 2001 From: "Ralf W. Grosse-Kunstleve" Date: Sun, 8 Oct 2023 22:38:19 -0700 Subject: [PATCH] Go back to using `union` as originally suggested by jbms@. The trick (also suggested by jbms@) is to add empty ctor + dtor. --- include/pybind11/numpy.h | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/include/pybind11/numpy.h b/include/pybind11/numpy.h index 5a60f18b2a..0a00120c90 100644 --- a/include/pybind11/numpy.h +++ b/include/pybind11/numpy.h @@ -21,7 +21,6 @@ #include #include #include -#include #include #include #include @@ -55,16 +54,21 @@ class LazyInitializeAtLeastOnceDestroyNever { // Multiple threads may run this concurrently, but that is fine. auto value = initialize(); // May release and re-acquire the GIL. if (!initialized_) { // This runs with the GIL held, - new // therefore this is reached only once. - (reinterpret_cast(value_storage_)) T(std::move(value)); + new (&value_) // therefore this is reached only once. + T(std::move(value)); initialized_ = true; } } - return *reinterpret_cast(value_storage_); + return value_; } + LazyInitializeAtLeastOnceDestroyNever() {} + ~LazyInitializeAtLeastOnceDestroyNever() {} + private: - alignas(T) char value_storage_[sizeof(T)]; + union { + T value_; + }; bool initialized_ = false; };