[C++-sig] memory leaks using the "manage_new_object"return policy...

Roman Yakovenko roman.yakovenko at gmail.com
Wed Sep 20 20:57:33 CEST 2006


On 9/20/06, Kevin Jones <investtcartier at yahoo.com> wrote:
> It turns out that the leak is in the return_by_value policy and *not* the
> manage_new_object policy.

It seems to me that youare doing something very strange here

> I am converting a "newed" C++ instance to a Python object and the C++ instance

Boost.Python does not know about "newed" object, you did not tell this to it.

> #include <vector>
> #include "boostpython.h"
>
> class BoostTest
> {
>     public:
>         int getSize(){return v.size();}
>         void append(int x){v.push_back(x);}
>         int getItem(int i){return v[i];}
>     private:
>         std::vector<int> v;
> };
>
> // Factory function for free store instances of BoostTest
> BoostTest* make(int n)
> {
>     BoostTest* b = new BoostTest();
>     for(int i=0;i<n;i++)
>     {
>         b->append(i);
>     }
>     return b;
> }
>
> struct BoostTest_to_p
> {
>     static PyObject* convert(BoostTest* x);
> };
>
> PyObject* BoostTest_to_p::convert(BoostTest* x)
> {
>     PyObject* list = PyList_New(0);
>     if(list == NULL) return Py_None;
>     const int n = x->getSize();
>     for(int i=0;i<n;i++)
>     {
>         PyObject* item = PyInt_FromLong(x->getItem(i));
>         if( item == NULL || item == Py_None )
>         {
>             Py_DECREF(list);
>             list = Py_None;
>             break;
>         }
>         PyList_Append(list,item);
>     }
>     return list;
> }

I don't know why do you need this wrapper. Instead of it change you function
return value:

std::auto_ptr< BoostTest > make(int n);

Boost.Python will do the rest.

Also I don't understand why and when you expected Boost.Python to delete x?
It knows nothing about its lifetime, you didn't tell that to him.
I suggest you to read one more time section in tutorials about call policies.

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



More information about the Cplusplus-sig mailing list