[C++-sig] Boost::Python Reference Counting

Jim Bosch talljimbo at gmail.com
Tue May 20 21:34:39 CEST 2014


On Tue, May 20, 2014 at 3:26 PM, Wojciech Mamrak <wmamrak at gmail.com> wrote:

> In your code, after the call del(container), Element::_container is a
> dangling pointer. Using
>
> .def("getElement", &Container::getElement, return_internal_reference<>())
>
> should prevent the deletion of container for as long as element
> variable will be alive, me understands (ties lifetime of _conteiner
> with Element's this). This is of course inconsistent with behaviour of
> your C++ code. One may ask a question why would anyone make her code
> inconsistent. The tutorial gives one argument:
> "Python users should not be able to crash the system just by using our
> C++ interface".
> The other is, if that code had been written in Python entirely, it
> would run perfectly fine. And call policies help us keep our C++ code
> intact in such cases (no need for smart pointers).
>
>
This solution supercedes (or, rather, extends) mine:
return_internal_reference uses with_custodian_and_ward under the hood, but
it's a much easier way to call it.  I didn't originally recognize that one
could use it here.

I think the OP was asking for a solution that does make the Python code
inconsistent with the C++ code in exactly this way (i.e. by making the
Python code safer), so I think think we're all in good agreement on that.

The only area where I think there might be disagreement is whether one
should rewrite the C++ code to use shared_ptr instead, and I don't think
it's worthwhile to try to have a general rule on that one way or the other.

Jim
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20140520/848b6605/attachment.html>


More information about the Cplusplus-sig mailing list