kkaempf / swig-issues

Issues from SWIG (testing)
0 stars 0 forks source link

C++ reference counting doesn't release memory #42

Open SwigAtSF opened 11 years ago

SwigAtSF commented 11 years ago

I have a number of classes (not written by me) that all derive from a shared parent class Referenced. This class Referenced has a method ref() and unref() which increase/decrease a reference count the class keeps. When the count goes 0 "delete this;" is called.

Because reference counting doesn't make sense for stack-allocated objects all destructors of these classes are protected (and virtual). There is also no need for them to be public, as memory management is implicitly done through the ref()/unref() methods.

When wrapping these classes with swig into a python module using the %refobject feature on Referenced, the following occurs: as the destructor of Referenced is protected it can't be wrapped and swig reports (at runtime) memory leaks because it can't call the destructor. However, the unref() method is also never called (although it is wrapped), it simply gets turned into an instance method of a Referenced object.

It seems to me that when reference-counting is requested using %refobject/%unrefobject any memory-management done by swig should be performed by calling the specified ref/unref methods. Instead of trying to wrap the destructor, I would expect a simple call to the unref method.

I attached an example, which includes a work-around by William Fulton, but I still consider this a bug...

SwigAtSF commented 11 years ago

example class showing the problem