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

David Abrahams david.abrahams at rcn.com
Thu Jan 24 02:43:13 CET 2002


Sorry I never replied to this...

----- Original Message -----
From: "Hugo van der Merwe" <s13361562 at bach.sun.ac.za>

> 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()); }


> Technically, the pointer returned by f() may point to an instance that
> some other part of the code has rw access to, so while the function
> calling f() can not change the object due to it being const, something
> else may still change it. Thus behaviour of the python object may be not
> as expected, since it has been copied, and a change in the original will
> not be reflected in the "python copy".

Right.

> 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

> I do not yet have a firm grasp of all things C++ related. I may be
> mistaken in my understanding?

No, you have grasped the conundrum.






More information about the Cplusplus-sig mailing list