Reference leaks in nanobind on the C++ side when Python exits
00:12 14 Nov 2025

Assume that we have C++ three classes A, B and C.

  • Class C has some floats.
  • Class B contains some stack allocated instances of class C
  • Class A contains raw pointers to class B instances and some vectors containing copies of class C instances in class B.

These classes are exposed to the Python side using nanobind. In Python I created two classes pA and pB that wrap A and B to act as a stub and include some Python only functionality.

The problem is that when Python exits, nanobind reports that all instances of A and B (allocated by Python classes pA and pB) have leaked and a whole bunch of functions. I applied the solution written in nanobind docs to class A but the leak of class A instances still exists.

How should I proceed and what about the mysterious function leaks?

python c++ nanobind