[C++-sig] thin wrapper example in docs...

Hugo van der Merwe s13361562 at bach.sun.ac.za
Thu Jan 24 10:28:34 CET 2002


> > The following example appears in the Pointers section of the
> > Boost.Python docs:
> >
> > const Foo* f(); // original function
> > const Foo& f_wrapper() { return *f(); }
> >   ...
> > my_module.def(f_wrapper, "f");
> >
> > Am I correct in thinking:
> >
> >  - Here f() returns a new pointer to an instance of Foo.
> >  - The Python f() call calls f_wrapper, which returns a reference to
> > this intance of Foo, which is then copied to a new instance created and
> > "tracked" by python, using Foo's copy constructor.
> >  - If f() creates a new instance of Foo, nothing disposes this instance,
> > is there then not a memory leak?
> 
> Yes. The appropriate wrapper for that case is one of these:
> 
> std::auto_ptr<Foo> f_wrapper() { return std::auto_ptr<Foo>(f()); }
> boost::shared_ptr<Foo> f_wrapper() { return boost::shared_ptr<Foo>(f()); }

So the docs require some updating, the example above (and the exception
handling). Though I guess with the rewrite currently ongoing, it's a
waste of time, as it will all have to be updated for the new
Boost.Python anyway?

Where can I read up more about how this boost::shared_ptr or
std::auto_ptr works? (Do these two do the same thing? Does this work
because of auto_ptr and shared_ptr's magic, or because Boost.Python does
certain things when it finds an auto_ptr or shared_ptr?)

> > This brings forwards another
> > thought: if the pointer points to an instance that is used elsewhere, it
> > cannot be disposed after it's been copied? So when, how and where must
> > the Foo* returned by f() be disposed?
> 
> You must decide whether f() is passing off ownership of the Foo or not. This
> problem is explained by the introductory text at
> http://www.boost.org/libs/python/doc/pointers.html

Is this passing off or not passing off the difference between auto_ptr
and shared_ptr? With one of the two, the wrapper function above should
automatically dispose of the instance, since it's been copied and is no
longer necessary, with the other it should not touch it, because it's
still in use somewhere in the C++ code. Right?

Thanks a lot,
Hugo




More information about the Cplusplus-sig mailing list