[C++-sig] call policies
David Abrahams
dave at boost-consulting.com
Thu Oct 17 22:03:52 CEST 2002
Stefan Seefeld <stefan.seefeld at orthosoft.ca> writes:
> hi there,
>
> I'm reading up on call policies but I'm not sure my case is
> covered there:
>
> I'v got an object handed back from a factory call. I pass
> this object to another object where the second one takes
> over ownership:
>
> Foo *foo = FooFactory();
> Bar *bar = BarFactory(foo);
>
> (with either
>
> Bar *BarFactory(Foo *);
>
> or
>
> Bar *BarFactory(auto_ptr<Foo>);
>
> signature. How do I express that in boost.python ? The
> 'custody_and_wart' policy expects two arguments, the object
^^^^^^^^^^^^^^^^
A very interesting re-spelling, to be sure!
> to be consumed as well as the consuming one. In my case
> the consumer is created in the call. Which policy do I need ?
Well, there's no provision in any of the CallPolicy models for
handing ownership for your C++ object away from a Python object. Think
about it: the C++ object is embedded inside some Python object. How do
you wrest its lifetime management away from that object? You can't.
However, if your C++ object is held by smart pointer, you can get
shared or sole ownership back from the Python object. So for example,
if you declare your Foo class_<> with auto_ptr<Foo> as its Holder, the
corresponding Python object can be passed to a wrapped function which
expects an auto_ptr<Foo> argument (which will cause the Python object
to lose ownership), and your FooFactory function can return
auto_ptr<Foo>. I suggested that FooFactory returns auto_ptr<Foo>
explicitly, because manage_new_object uses boost::shared_ptr<> as a
workaround for one broken compiler (Intel C++ 5), though
manage_new_object would work find for any other compiler.
Bar* BarFactory(std::auto_ptr<Foo> foo);
class_<Foo, std::auto_ptr<Foo> >("Foo")
...
;
HTH,
Dave
--
David Abrahams
dave at boost-consulting.com * http://www.boost-consulting.com
Building C/C++ Extensions for Python: Dec 9-11, Austin, TX
http://www.enthought.com/training/building_extensions.html
More information about the Cplusplus-sig
mailing list