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

abeyer at uni-osnabrueck.de abeyer at uni-osnabrueck.de
Mon Aug 11 10:54:03 CEST 2003


> abeyer at uni-osnabrueck.de writes:
>
>> I.e. the identity is not preserved. Could this be a problem with MinGW,
>> which I am using?
>> To be sure, here is the complete code again:
>>
>> #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; }
>> 	A_ptr get() { return this->a; }
>> 	void f() { a.get()->val *= 2; }
>>      private:
>> 	 A_ptr a;
>> };
>>
>> BOOST_PYTHON_MODULE(ptr_test)
>> {
>>     using namespace boost::python;
>>     class_<A, A_ptr>("A", init< int >() )
>> 	.def_readwrite("val", &A::val)
>>     ;
>>     class_<C>("C" )
>> 	.def("set", &C::set )
>>         .def("get", &C::get )
>>         .def("f",   &C::f )
>>     ;
>> }
>
> OK, I understand the problem now.  It's not a MinGW issue.  The
> problem is that when you ask for A to be held by A_ptr, an A_ptr
> lvalue converter gets registered, since there is actually an A_ptr
> object inside the Python wrapper.  Lvalue converters can be used where
> only an rvalue is needed, as in:
>
>      void set(A_ptr a)
>
> and they get special priority over rvalue converters.  The only way to
> get the behavior you want is actually to NOT hold A objects by A_ptr:
>
>     class<A>("A", init<int>() )
>        ...
>
> so that the rvalue converter that gets registered can be found.
>
> Clearly, we need special rules for shared_ptr, so that this won't
> happen.  I'm just not sure whether we need special rules for all
> smart pointer types, yet.  Any thoughts?
>

Now it works great.

1. No, I do not think we need special rules for every smart pointer.
However, shared_ptr is explicitely mentioned for this problem in the FAQ.
Maybe we need rules for shared_ptr.

2. It would be great to put the above example into the Howto/FAQ. (Maybe
along with a few comments on lvalue/rvalue conversion.)

Thanks for the help,
   Andreas






More information about the Cplusplus-sig mailing list