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.
The top 3
- Pybind11's `smart_holder`: Solving Smart Pointer Interoperability: Classic Pybind11 often faced undefined runtime behavior, including segmentation faults, when attempting conversions or interoperation between `std::unique_ptr` and `std::shared_ptr` as class holders, a critical issue `smart_holder` resolves by providing robust, well-defined semantics.
- Top 3 `smart_holder` Advantages for Complex Bindings: `smart_holder` offers simultaneous two-way Python/C++ conversions for both `std::unique_ptr` and `std::shared_ptr`, safely disowns Python objects passed to C++ via `std::unique_ptr`, and ensures correct lifetime management for C++ virtual functions overridden in Python ("trampoline" objects).
- `smart_holder` Adoption: v3.0 Integration & Compatibility: Fully integrated into Pybind11 v3.0, `smart_holder` is now the recommended holder for most situations, easily activated by replacing `py::class_<T>` with `py::classh<T>`. However, modules built with `smart_holder` may not be ABI-compatible with those built using older Pybind11 versions.
Sources
Open the full topic