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

Mike Stoddart stodge at gmail.com
Sat May 3 02:11:44 CEST 2008


Hi folks, new to Boost Python and struggling to build a prototype at work. I
thought I'd start with a conceptual question to help clarify my
understanding. I already have a basic prototype working nicely but I'm
having a few issues, which I may post about later.

A brief functional rundown of what I'm trying to prototype. Hopefully my
explanation doesn't get too confusing!

I'm embedding a python module into an application;
Python will provide application
logic, responding to events such as timers expiring or the user
clicking widgets.

I have the following classes I'm exporting to Python:

Entity, DerivedEntity, EntityList (contains pointers to Entity).

They all
have varying types of copy/constructors, e.g. some are private, some
have non-const copy constructors etc. It's inherited code that I can't
mess with so I'm stuck with it.

So the typical logic flow I'm looking at is:

C++ Application:

- Create an instance of EntityList called entity_list, populate with many
instances of DerivedEntity.
- Create an instance of EntityList called change_list
- Invoke python function passing entity_list and change_list as parameters

Python:

- For each entity in entity_list:
    - Invoke C++ function clone_entity, pass entity as parameter

    C++ Application:

    - Create clone of entity like this --> DerivedEntity* entity_copy =
new DerivedEntity(entity)
    - return entity_copy to Python

Back in Python again:

    - Apply logic to entity_copy returned from clone_entity C++ function
    - If entity_copy updated add to change_list

Back in C++ Application:

- For each new_entity in change_list
    - Apply further logic to new_entity
    - Delete new_entity pointer
- Clear the change_list

I'm having problems in my prototype - it looks like I have a memory leak but
I'm not sure where. So my question is, what should I be aware of in this
logic flow with regards to object ownership and lifetime?

When I receive entity_copy in Python, returned from
clone_entity, what happens to this object when I insert it into
change_list and subsequently delete the C++ pointer? I don't know how
to prove that the Python object is being deleted and isn't hanging
around due to a lifetime issue,

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.

So if any of this makes sense, I would greatly appreciated any suggestions
or help. I'm very impressed with Boost Python so far but my own lack of
understanding is holding me back I think.

Thanks again
Mike
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20080502/35efa774/attachment.htm>


More information about the Cplusplus-sig mailing list