[C++-sig] Boost::Python - Question about object ownership and lifetime

Hans Meine hans_meine at gmx.net
Tue May 6 20:46:59 CEST 2008


On Samstag 03 Mai 2008, Mike Stoddart wrote:
> I guess my main problem is that I'm entirely sure I understand object
> ownership - who owns what object when it's created in C++, passed to Python
> and then returned back to C++ to be deleted.

I may be far off with my answer since I skipped nearly everything above this 
paragraph of yours, but let me shoot in the dark:

IMO it helps if you understand reference counting (I assume you do); now you 
must know that python always has reference counting, which you cannot turn 
off, and you cannot write a C++ function which deletes a Python object (you 
cannot delete the references that still exist in python, which include the 
deleting function's argument).  So there are the following possibilities:
Use refcounting in C++, too, and let python objects hold at least one 
reference to the C++ object (e.g. using shared_ptr<> as held type), use other 
means to make sure that the C++ object never vanishes throughout the lifetime 
of the Python objects (e.g. I sometimes let more complex Python object "a" 
hold a reference to a C++ array, and I assume that smaller Python 
objects "b_i" - e.g. returned from a.__getitem__ - do not live longer than a 
and do not need their own C++ lifetime management, but this is not the clean 
way), or catch the case that the C++ object has been deleted and throw 
exceptions whenever the corresponding Python objects are tried to be accessed 
(AFAICS, this way is chosen by sip/PyQt, but it is very uncommon with the 
BPL).

-- 
Ciao, /  /                                                    .o.
     /--/                                                     ..o
    /  / ANS                                                  ooo
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: This is a digitally signed message part.
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20080506/5304c01e/attachment.pgp>


More information about the Cplusplus-sig mailing list