[C++-sig] Re: Containers for derived classes

David Abrahams dave at boost-consulting.com
Wed Aug 6 21:42:18 CEST 2003


abeyer at uni-osnabrueck.de writes:

>>> However, the FAQ says there are more elegant ways by using
>>> boost::shared_ptr:
>>> "When a shared_ptr<X> is converted back to Python, the library checks to
>>> see if it's one of those "Python object managers" and if so just returns
>>> the original Python object."
>>>
>>> I have played with it, but I had no luck so far.
>>
>>What did you do?  Please post some code which illustrates.
>>
>>> Has anyone an example using shared_ptr that fits my purpose?
>>
>>If you make C a container of shared_ptr<A>, it should just work.
>
> OK, this is what I have tried:
>
> --- begin ptr_test.cpp
>
> #include <boost/shared_ptr.hpp>
> #include <boost/python.hpp>
>
> using namespace boost;
>
> class A {
>      public:
> 	A(int i) : val(i) { }
> 	int val;
> };
> typedef shared_ptr<A> A_ptr;
>
> class C {
>      public:
> 	void set(A_ptr& a) { this->a=a; }
             ^^^^^^

This is your problem.  Use A_ptr const& or better yet, plain A_ptr.

Using a non-const reference means that Boost.Python has to find an
actual A_ptr object within the source Python object.

> 	A_ptr& get() { return this->a; }

Likewise, you'd be better off just returning by-value here.


-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com





More information about the Cplusplus-sig mailing list