[C++-sig] [Py++] boost::shared_ptr casting

peoro peoro.noob at gmail.com
Sat Mar 20 21:31:22 CET 2010


Hello,

I'm having some issues with shared_ptr's in a Python environment: it
looks like once a shared_ptr enters Python, it cannot be upcasted nor
downcasted.

Here's a brief C++ source code to explain better the issue:


#include <boost/shared_ptr.hpp>

class Base { };
class Derived : public Base { };

boost::shared_ptr<Base> base1( ) {
  return boost::shared_ptr<Base>( new Base );
}
boost::shared_ptr<Base> base2( ) {
  return boost::shared_ptr<Base>( new Derived );
}
boost::shared_ptr<Base> base3( boost::shared_ptr<Derived> derived ) {
  return boost::shared_ptr<Base>( derived );
}
boost::shared_ptr<Derived> derived1( ) {
  return boost::shared_ptr<Derived>( new Derived );
}
boost::shared_ptr<Derived> derived2( boost::shared_ptr<Base> base ) {
  return boost::static_pointer_cast<Derived>( base );
}


then, after building the library and importing it into Python, I would
expect something like this:


from shared_ptr_inheritance import *
type( base1() ) -> Base
type( base2() ) -> Base
type( derived1() ) -> Derived
type( base3( derived1() ) ) -> Base
type( derived2( base2() ) ) -> Derived


but instead, this is the actual behaviour:


from shared_ptr_inheritance import *
type( base1() ) -> Base
type( base2() ) -> Base
type( derived1() ) -> Derived
type( base3( derived1() ) ) -> Derived (!!!)
type( derived2( base2() ) ) -> Base (!!!)


am I doing something wrong?
why does this happen, and, mostly, how can I cast a shared_ptr<Base>
containing a Derived pointer, to shared_ptr<Derived> ?


More information about the Cplusplus-sig mailing list