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

Bruce Lowery bruce_lowery at yahoo.com
Tue Feb 4 22:06:43 CET 2003


It took much longer for me to compose the message than it did for you to solve
and answer it.   As always, Thanks.

Bruce lowery

--- Dave Abrahams <dave at boost-consulting.com> wrote:
> 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
> 
> 
> _______________________________________________
> C++-sig mailing list
> C++-sig at python.org
> http://mail.python.org/mailman/listinfo/c++-sig


__________________________________________________
Do you Yahoo!?
Yahoo! Mail Plus - Powerful. Affordable. Sign up now.
http://mailplus.yahoo.com




More information about the Cplusplus-sig mailing list