[C++-sig] newbie questions
David Abrahams
dave at boost-consulting.com
Tue Oct 8 16:38:42 CEST 2002
Stefan Seefeld <seefeld at sympatico.ca> writes:
> David Abrahams wrote:
>
> > 1. Are you trying to wrap an interface without changing it? In other
> > words, is it OK to change the definition of Foo, Bar, and BarImpl,
> > or is this wrapping job to be non-intrusive?
>
> ideally it's non-intrusive. I'm all for cleaning it up (and it needs
> some cleanup !), but that's not my (current) mandate...
>
> > 2. What is the semantics of GetBar()? Does it just return a pointer to
> > some BarImpl, to be used as a kind of reference, or is it the
> > caller expected to delete (or otherwise manage) the pointer it gets
> > back?
>
> in this particular case Foo remains the owner.
>
> > 3. If the BarImpl* is just a kind of reference, which object actually
> > manages the lifetime of the BarImpl object?
>
> Foo.
>
> I guess in all other cases I would use the factory approach we
> discussed yesterday.
>
> Regards,
> Stefan
Okay, revisiting your code in that light:
class Bar {};
class BarImpl : public Bar {};
class Foo
{
public:
BarImpl *GetBar();
};
you need this part no matter what:
class_<Bar>("Bar")
...
;
option 1: expose the BarImpl class too:
class_<BarImpl, bases<Bar> >("BarImpl", no_init)
;
class_<Foo>("Foo")
.def("GetBar", &Foo::GetBar
, return_value_policy<return_internal_reference>())
...
;
The only downside of that is that Python users might detect that
there's a BarImpl class as well as a Bar class. But so what?
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>())
...
;
HTH,
Dave
P.S. I suggest you read up on CallPolicies in the documentation I sent
you pointers to.
--
David Abrahams * Boost Consulting
dave at boost-consulting.com * http://www.boost-consulting.com
More information about the Cplusplus-sig
mailing list