Skip to content

Commit

Permalink
Go back to using union as originally suggested by jbms@. The trick …
Browse files Browse the repository at this point in the history
…(also suggested by jbms@) is to add empty ctor + dtor.
  • Loading branch information
Ralf W. Grosse-Kunstleve committed Oct 9, 2023
1 parent 38317c3 commit e7b8c4f
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 deletions include/pybind11/numpy.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
#include <functional>
#include <numeric>
#include <sstream>
#include <stdalign.h>
#include <string>
#include <type_traits>
#include <typeindex>
Expand Down Expand Up @@ -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<T *>(value_storage_)) T(std::move(value));
new (&value_) // therefore this is reached only once.
T(std::move(value));
initialized_ = true;
}
}
return *reinterpret_cast<T *>(value_storage_);
return value_;
}

LazyInitializeAtLeastOnceDestroyNever() {}
~LazyInitializeAtLeastOnceDestroyNever() {}

private:
alignas(T) char value_storage_[sizeof(T)];
union {
T value_;
};
bool initialized_ = false;
};

Expand Down

0 comments on commit e7b8c4f

Please sign in to comment.