You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When returning a shared_ptr to a bound object from a C++ function, the object seems to be immediately destructed, although it continues to be "usable" from Python, but this is dangerous, because it is a "dangling" object.
What I think would be more appropriate in this case:
Give an error message stating that a function may not return shared_ptr of an object when it's holder type is the default one.
If that is not possible, at least let the function return None, this is way less dangerous.
Note that the object ends up being destructed twice!
deftest_bindings_problem():
import_pb11pg_pb11pg.reset_called()
x=_pb11pg.create_bindings_test()
# Destructor was already called hereassertx.get_status() =='OK'assert_pb11pg.get_constructor_called() ==1assert_pb11pg.get_destructor_called() ==0x=Noneassert_pb11pg.get_constructor_called() ==1assert_pb11pg.get_destructor_called() ==1
Workaround
Use shared_ptr as a holder type, but the problem is that it is very hard to find that this is the issue causing the segfaults and unexpected behaviours:
py::class_<BindingsTest, shared_ptr<BindingsTest>> instead of py::class_<BindingsTest>
The text was updated successfully, but these errors were encountered:
I believe the problem might actually be that you're mixing holder types (where py::class_<BindingsTest> = py::class_<BindingsTest, std::unique_ptr<BindingsTest>>). See #1138 and #1161 for more details.
From what I understand, py::class_ stores the holder in a type-erased fashion, and upon casting to/from a possible holder type (e.g. unique_ptr or shared_ptr), it will not check the types, and effectively do a bad reinterpret_cast, interpreting memory allocated for unique_ptr as shared_ptr. #1161 could provide a mechanism to detect this.
Issue description
When returning a
shared_ptr
to a bound object from a C++ function, the object seems to be immediately destructed, although it continues to be "usable" from Python, but this is dangerous, because it is a "dangling" object.What I think would be more appropriate in this case:
shared_ptr
of an object when it's holder type is the default one.None
, this is way less dangerous.Note that the object ends up being destructed twice!
Reproducible example code
Workaround
Use
shared_ptr
as a holder type, but the problem is that it is very hard to find that this is the issue causing the segfaults and unexpected behaviours:py::class_<BindingsTest, shared_ptr<BindingsTest>>
instead ofpy::class_<BindingsTest>
The text was updated successfully, but these errors were encountered: