`py::smart_holder`'s Solution to Inheritance Slicing
For C++ classes with virtual functions subclassed in Python (trampoline classes), `py::smart_holder` (Pybind11v3+) is crucial. It prevents 'inheritance slicing' by ensuring the derived Python object remains alive when a `std::shared_ptr` to it is held in C++, creating an independent control block.
The top 3
- Inheritance Slicing: The Top Pitfall for C++-Python Polymorphism: Inheritance slicing occurs when a derived C++ object is implicitly converted to a base class object by value, losing all derived-specific data and methods. This is a critical issue for `pybind11` as it breaks polymorphic behavior and can lead to incorrect function calls or even segmentation faults when Python interacts with C++ hierarchies.
- `py::smart_holder`'s Unique `shared_ptr` Wrapper for Type Fidelity: `py::smart_holder` prevents inheritance slicing by employing a type-erased wrapper around `std::shared_ptr`. When converting a Python object to `std::shared_ptr<T>`, it creates an independent control block that keeps the *derived* Python object alive, ensuring the correct type information is preserved across the C++ and Python boundary.
- `smart_holder`: The Key to Seamless C++ Downcasting in Python: By preserving the true derived type, `py::smart_holder` enables `pybind11` to perform automatic downcasting. This allows Python code to correctly recognize the concrete derived C++ type, access its specific functions and attributes, and maintain full polymorphic behavior without explicit type checks, even when dealing with objects passed via base class pointers.
Sources
Open the full topic