[C++-sig] How to deep-copy and delete a mixed python/C++ object from C++
Achim H.
achim-bpl at mol-net.com
Mon Apr 3 11:11:27 CEST 2006
Am Freitag, 31. März 2006 19:57 schrieb Paul F. Kunz:
> >>>>> On Fri, 31 Mar 2006 10:48:01 +0200, "Achim H."
> >>>>> <achim-bpl at mol-net.com> said:
> >
> > How can I achieve both correct copying and deletion semantics ?
>
> I'm not sure about deletion, but here is how I do the copying (with
> a lot of help from Dave Abrahams)...
>
>
>
http://www.slac.stanford.edu/grp/ek/hippodraw/lib/FunctionWrap_8cxx-source.html#l00179
I came to a similar solution, in my case not refering directly to the owning
python object, but looking up the class in the __main__ namespace (class name
was present as a member for introspection reasons anyway). Your solution is
more widely applicable (though at the moment only working in the case that
there is no python override, as David Abrahams pointed out). I will therefore
probably adopt your strategy.
However, your way of cloning IMHO creates the same chicken-and-egg problem
regarding ownership as my Wrapper did when I played around: the Wrap is owned
by the python object and the python object is owned by the wrap. A delete on
the Wrap will auto-destruct the python object, that will then try to delete
the Wrap.
If you try to delete it from the C++ side, you will get an error (e.g.,
SIGSEGV). I'm not totally sure whether Python at the end tries to delete all
objects still being around. If python does not, you created a memory leak
which probably is a minor concern to you if you don't have many instances of
FunctionWrap around.
I myself played around with an arbitrary Py_INCREF() which at first only
postponed the error message to the program end. When I started to also employ
boost::shared_ptr<> (class_<shared_ptr<Wrap> ...>), it vanished. Don't ask me
why, it kind of works for me now. Still, I would like to understand the
situation better and use a correct solution, not only one that works in most
of the cases or on my current platform.
Any how, thanks for your help, it at least provides me with a better
implementation of the clone() method, though the ownership issues are still
unsolved for me.
Achim.
More information about the Cplusplus-sig
mailing list