c++ - 使用 boost::shared_ptr 进行多态转换

标签 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);

最佳答案

使用 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++ TR1 库中的 std::tr1 命名空间03.)

关于c++ - 使用 boost::shared_ptr 进行多态转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14490190/

相关文章:

c++ - 通过 boost::lexical_cast 将 C++Builder AnsiString 转换为 std::string

c++ - ABC 中的多态静态常量成员变量?

c++ - 隐藏抽象基类的复制构造函数

c++ - 在 catch block 异常中无意义地使用引用传递语法?

c++ - weak_ptr 或 shared_ptr 应该从 unique-owner-collection 返回吗?

c++ - boost::thread 应该在无限循环中运行并等待没有互斥量的新输入

c++ - 使用 boost::filesystem 遍历目录而不抛出异常

c++ - NSight 中的 CUDA 架构 -sm_11 编译问题

c++ - 如何在 UVA 上编译以下内容?

C++: protected 类构造函数