static_castboost::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 = ???
有帮助吗?

解决方案

使用boost::static_pointer_cast

boost::shared_ptr<Base> b(new Derived());
boost::shared_ptr<Derived> d = boost::static_pointer_cast<Derived>(b);

其他提示

智能指针有三个强制转换操作符:static_pointer_castdynamic_pointer_castconst_pointer_cast。它们位于命名空间boost(由<boost/shared_ptr.hpp>提供)或命名空间std::tr1(由Boost或编译器的TR1实现提供)。

作为评论:如果Derived实际上是从Base派生的,那么你应该使用dynamic_pointer_cast而不是静态强制转换。系统将有机会检测你的演员阵容何时/是否正确。

值得一提的是,Boost提供的铸造运营商数量与TR1的实施存在差异。

TR1没有定义第三个运算符const_pointer_cast()

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top