[C++-sig] newbie questions
David Abrahams
dave at boost-consulting.com
Tue Oct 8 18:29:12 CEST 2002
Stefan Seefeld <seefeld at sympatico.ca> writes:
> David Abrahams wrote:
>
> > you need this part no matter what:
> > class_<Bar>("Bar")
> > ...
> > ;
>
> with just one 'Bar' template parameter ? Wouldn't that mean
> that each python instance would hold its own 'Bar' *object* ?
Not neccessarily. It just affects how the Bar object is held when you
construct one from Python:
>>> b = Bar() # Held by-value or,e.g., by shared_ptr<Bar>?
> I'm dealing with references (pointers), after all, whether I
> own them or not...
That's OK. When you use return_value_policy<manage_new_object> the
pointer gets embedded in and managed by a new Python object. When you
use return_value_policy<return_internal_reference<> > the pointer gets
embedded in a new Python object and the other Python object wrappers
have their lifetimes tied together so that the containing object won't
be destroyed until the new object is.
> > option 2: use a thin wrapper to hide the existence of BarImpl:
> > Bar* foo_GetBar(Foo& f) { return f.GetBar(); }
> > class_<Foo>("Foo")
> > .def("GetBar", foo_GetBar
> > , return_value_policy<return_internal_reference>())
> > ...
> > ;
>
> ok, tried that (plus the '<>' you mention in another mail), but
> I get linker errors as some types are not to be found, or incomplete.
I can't help with that unless you post the linker errors.
> But what speaks against using shared_ptr with my own (dummy) deleter ?
>
> I try this:
>
> template<class T> struct dummy_deleter
> {
> typedef void result_type;
> typedef T * argument_type;
>
> void operator()(T * x){}
> };
>
> boost::shared_ptr<Bar> Foo_GetBar(Foo &foo, int i)
> {
> return boost::shared_ptr<Bar>(foo.getBar(),
> dummy_deleter<Foo>());
> }
Umm, memory leaks and dangling shared_ptrs do.
> and then simply declare
>
> foo.def("getBar", Foo_GetBar);
>
> and it works. Is this a 'correct' way of doing it ?
Not very, unless it's OK for Python code using your wrapper to crash
the system. The C++ Bar object can still be deleted out from under the
shared_ptr that refers to it.
--
David Abrahams * Boost Consulting
dave at boost-consulting.com * http://www.boost-consulting.com
More information about the Cplusplus-sig
mailing list