使用这种智能指针投射是否安全?
APtr a(new A());
BPtr & b = (Bptr&)a; // this is it
那里,
class A
{
public:
virtual ~A(){}
virtual void methodA() = 0;
}
typedef std::tr1::shared_ptr<A> APtr;
class B : public A
{
public:
virtual ~B(){}
virtual void methodB() = 0;
}
typedef std::tr1::shared_ptr<B> BPtr;
/////////////////////////////////////////////////////////////////////////////////
BPtr & b = a; //this way doesn't work
最佳答案
要向下转换智能指针,您应该使用xxxx_pointer_cast函数,例如一个static cast
BPtr b = std::tr1::static_pointer_cast<B>(a);
或dynamic cast
BPtr b = std::tr1::dynamic_pointer_cast<B>(a);