Pybind11's Broad Support for Modern C++ Smart Pointers
Pybind11 natively supports `std::unique_ptr` (as the default holder for `py::class_`), `std::shared_ptr`, and `std::weak_ptr` for various ownership patterns. Beyond standard library types, it also allows users to enable transparent conversions for custom smart pointers via the `PYBIND11_DECLARE_HOLDER_TYPE` macro.
The top 3
- Pybind11's `py::smart_holder`: Unifying C++ Ownership: Introduced in pybind11 v3, `py::smart_holder` (or its shorthand `py::classh<T>`) is the recommended holder type, offering simultaneous two-way conversion support for both `std::shared_ptr` and `std::unique_ptr` and full integration with `std::enable_shared_from_this` for robust memory management.
- `std::shared_ptr`: Seamless C++/Python Shared Ownership: Pybind11 natively supports `std::shared_ptr` as a holder type for C++ objects, enabling seamless shared ownership and correct reference counting between C++ and Python. This prevents common memory errors like double-frees and ensures proper object lifetime management across language boundaries.
- `std::unique_ptr`: Default Holder for Exclusive C++ Ownership: `std::unique_ptr` is the default holder type for `py::class_` when no explicit holder is specified, allowing C++ functions to return objects with exclusive ownership to Python. However, Python cannot typically pass `std::unique_ptr` as function arguments due to differences in ownership semantics, as Python objects might have multiple references.
Sources
Open the full topic