Pybind11's Smart Pointer Mastery
It natively understands and manages C++ smart pointers (e.g., `std::shared_ptr`, `std::unique_ptr`), ensuring correct memory ownership and preventing leaks across the C++/Python boundary with minimal effort.
The top 3
- Pybind11's `smart_holder` vs. Classic Smart Pointer Bindings: Pybind11 v3.0 introduced `py::smart_holder` as the recommended class holder, offering robust two-way conversion for `std::unique_ptr` and `std::shared_ptr` simultaneously, resolving long-standing issues and improving interoperability that was missing in classic Pybind11, where mixing `unique_ptr` and `shared_ptr` as holders could lead to undefined behavior.
- Bridging C++ `shared_ptr` to Python Object Lifecycles: Pybind11 ensures correct memory management by bridging C++ `std::shared_ptr` and Python's garbage collection. Using `py::smart_holder`, a C++ object managed by `std::shared_ptr` can be converted to a Python object, creating a new `shared_ptr` control block that keeps the Python object alive and prevents inheritance slicing. It also supports `std::enable_shared_from_this`.
- 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.
Sources
Open the full topic