static_cast与with等效boost::shared_ptr吗?
换句话说,我该如何重写以下内容
Base* b = new Derived();
Derived* d = static_cast<Derived*>(b);
什么时候使用shared_ptr?
boost::shared_ptr<Base> b(new Derived());
boost::shared_ptr<Derived> d = ???
Answers:
用途boost::static_pointer_cast:
boost::shared_ptr<Base> b(new Derived());
boost::shared_ptr<Derived> d = boost::static_pointer_cast<Derived>(b);
boost::static_pointer_cast<Derived>(b)也可以作为Base隐式使用。
有三种类型转换操作符的智能指针:static_pointer_cast,dynamic_pointer_cast,和const_pointer_cast。它们位于命名空间boost(由提供<boost/shared_ptr.hpp>)或命名空间std::tr1(由Boost或编译器的TR1实现提供)中。
作为评论:如果Derived实际上是从Base派生的,那么您应该使用dynamic_pointer_cast而不是静态强制转换。系统将有机会检测您的投放时间是否正确。
Base *b = new Derived();吗?