[C++-sig] Custom memory management

Niall Douglas s_sourceforge at nedprod.com
Sat Jul 30 02:52:46 CEST 2005

On 29 Jul 2005 at 11:28, Eric Jardim wrote:

> The problem is that Qt has a light "garbage collection" scheme. Every
> "QObject" object that you create must has a "parent" object (except
> toplevels). When the object is deleted, it clean all the mess of its
> children and so on.
> Maybe, child objects are beeing killed too soon and the parents can't
> find them. I am using the with custodian and ward at the constructors,
> but sometimes I do not create the object.

Custodian and ward won't help you here. This is happening because 
python likes to manage the lifetime of its objects and doesn't know 
when Qt deletes them from underneath it.

> Besides, I suspect that I reference the same C++ object more than one
> time which might be a problem.

Shouldn't be. BPL refcounts.

> Any ideas of what I can do to manage this memory problem? I dropped
> here the backtrace of one the segfaults.

Make your wrappers hold an auto_ptr to your Qt objects. This works as 
you'd expect it. Upcall when Qt deletes an object to the python layer 
so it zeros the auto_ptr so python won't delete anything later. If 
you want to see it in action, see how TnFOX does it at 
http://www.nedprod.com/TnFOX/ (get the most recent snapshot).


More information about the Cplusplus-sig mailing list