Skip to content

Commit

Permalink
std::shared_ptr<T> bindings: avoid leaks at interpreter shutdown
Browse files Browse the repository at this point in the history
The ``nb::shared_ptr<T>`` binding implementation may sometimes need to
create a shared pointer wrapper around an object that was originally
constructed in Python. Eventual expiry of this shared pointer will
decrease the reference count of the underlying Python object. However,
this is unsafe to do when Python is already shut down, which the
implementation previously checked by querying ``Py_IsInitialized()``.

It turns out that this is a bit too conservative since it also prevents
proper cleanup *during* shutdown time/finalization
(``Py_IsInitialized()`` already returns zero at this point). This commit
changes the criterion to ``nb::is_alive()``.
  • Loading branch information
wjakob committed Jan 6, 2025
1 parent ddfbe92 commit fb81576
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion include/nanobind/stl/shared_ptr.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ NAMESPACE_BEGIN(detail)
struct py_deleter {
void operator()(void *) noexcept {
// Don't run the deleter if the interpreter has been shut down
if (!Py_IsInitialized())
if (!is_alive())
return;
gil_scoped_acquire guard;
Py_DECREF(o);
Expand Down

0 comments on commit fb81576

Please sign in to comment.