使用boost :: shared_ptr进行多态转换

时间:2013-01-23 21:59:58

标签: c++ boost polymorphism smart-pointers

我熟悉普通指针的boost polymorphic_cast

Base *base;

Derived *d = boost::polymorphic_cast<Derived>(base);

但是,如何将它与boost::shared_ptr一起使用?

boost::shared_ptr<Base> base;

boost::shared_ptr<Derived> d = boost::?????(base);

1 个答案:

答案 0 :(得分:2)

使用boost::static_pointer_castboost::dynamic_pointer_cast作为C ++演员static_castdynamic_cast的类似物:

boost::shared_ptr<Derived> d = boost::static_pointer_cast<Derived>(base);

// now "d" shares ownership with "base"

这只是对底层原始指针执行相应的强制转换。

(在C ++ 11标准库的std命名空间和C ++ 03的TR1库中的std::tr1命名空间也是如此。)