[C++-sig] Garbage Collector and C++ objects lifetime

Roman Yakovenko roman.yakovenko at gmail.com
Mon Jan 21 19:52:06 CET 2008


2008/1/21 progetto dex <progettodex at gmail.com>:
> Hi,
> I'm using boost.python to expose a C++ API to Python, and I'm facing a
> problem concerning the C++ object lifetime and python's garbage collector.
> The C++ API is based on a Session object that abstracts a connection towards
> a RDBMS, and let the client access a Documents object, which in turn exposes
> a DOM inspired Document object list, made up of a variable number of Element
> objects. Documents is owned by Session, and returns pointers to Document
> objects. Elements are implemented as custom smart pointers (ref-count
> idiom). I've successfully wrapped all this stuff, but a problem raises when
> I instantiate some Elements from Python: the program crashes on exit. The
> reason is that every Element has an internal reference to the Session (well,
> to an abstract Observer that happens to be the Session), and Python releases
> the Session object before the Element. Instantiating a static Session on the
> C++ side, and using that object instead of the Python's one, every thing
> works fine. Can I tell Python that a custodian/ward relationship exists
> between these two objects, given the fact that no one knows nothing about
> the other (except from Element expecting an abstract Observer)? Is there any
> other construct/technique that I could adopt to solve this problem?

If you instantiate Elements from Python, than you can store on an
element instance reference to the Session, thus preventing Python to
distract the it earlier.

-- 
Roman Yakovenko
C++ Python language binding
http://www.language-binding.net/



More information about the Cplusplus-sig mailing list