[C++-sig] Can ownership of a wrapped C++ object be transferred between python objects?

Dave Abrahams dave at boost-consulting.com
Tue Feb 4 21:23:38 CET 2003


On Tuesday, February 04, 2003 3:09 PM [GMT+1=CET],
Bruce Lowery <bruce_lowery at yahoo.com> wrote:

> Part of an API that I'm wrapping goes something like this:
>
> struct A {}; struct B { void insert( A* ); }
> where B::add() takes ownership of the pointer passed to it.
>
> However:
>
> a = mod.A()
> b = mod.B()
> b.add( a )
> del a
> del b
> # python interpreter crashes
> # later due to memory corruption.
>
> Even binding the lifetime of 'a' to 'b' via with_custodian_and_ward
doesn't
> prevent the python object 'a' from ultimately trying to delete the object
> it's pointing to (right? - I tried anyway and didn't see any improvement).

Right.  with_custodian_and_ward adds more lifetime management from the
Python side, and you need less ;-)

> Is there a way to accomplish a 'transfer-of-ownership' of a wrapped C++
> object?

Yes: Make sure the C++ object is held by auto_ptr:

    class_<A, std::auto_ptr<A> >("A")
        ...
        ;

Then make a thin wrapper function which takes an auto_ptr parameter:

    void b_insert(B& b, std::auto_ptr<A> a)
    {
        b.insert(a.get());
        a.release();
    }

Wrap that as B.add.

HTH,
--
Dave Abrahams
Boost Consulting
http://www.boost-consulting.com





More information about the Cplusplus-sig mailing list