gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:52:14 24 4
gpt4 key购买 nike

我熟悉 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com