--- include/pybind11/pytypes.h 2020-09-30 16:58:36.000000000 +0800 +++ include/pybind11/pytypes.h 2020-09-30 16:59:50.000000000 +0800 @@ -237,7 +237,11 @@ /// Move constructor; steals the object from ``other`` and preserves its reference count object(object &&other) noexcept { m_ptr = other.m_ptr; other.m_ptr = nullptr; } /// Destructor; automatically calls `handle::dec_ref()` - ~object() { dec_ref(); } + ~object() { + if (stolen == false) { + dec_ref(); + } + } /** \rst Resets the internal pointer to ``nullptr`` without without decreasing the @@ -276,6 +280,7 @@ // Tags for choosing constructors from raw PyObject * struct borrowed_t { }; struct stolen_t { }; + bool stolen = false; template friend T reinterpret_borrow(handle); template friend T reinterpret_steal(handle); @@ -283,7 +288,7 @@ public: // Only accessible from derived classes and the reinterpret_* functions object(handle h, borrowed_t) : handle(h) { inc_ref(); } - object(handle h, stolen_t) : handle(h) { } + object(handle h, stolen_t) : handle(h), stolen(true) { } }; /** \rst @@ -1481,4 +1486,4 @@ #undef PYBIND11_MATH_OPERATOR_BINARY NAMESPACE_END(detail) -NAMESPACE_END(PYBIND11_NAMESPACE) +NAMESPACE_END(PYBIND11_NAMESPACE) \ No newline at end of file