微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 C++ 中没有 std::static_pointer_cast 的情况下向下转换 shared_ptr?

如何解决如何在 C++ 中没有 std::static_pointer_cast 的情况下向下转换 shared_ptr?

我们使用 EASTL 而我不能使用 std::static_pointer_cast。
我在我的函数中收到一个指向基类的指针,但不知道如何正确转换它:

    switch (command.code)
    {
..
    case CommandCode::firstCase:
        firstCaseFunction(std::shared_ptr<firstCaseType>(static_cast<firstCaseType*>(command.context.get())));
        break;
    case CommandCode::secondCase:
        secondCaseFunction(std::shared_ptr<secondCaseType>(static_cast<secondCaseType*>(command.context.get())));
        break;
..
    default:
        break;
    }

上面的代码可以编译,但是在 firstCaseFunction/secondCaseFunction 的末尾抛出了一些异常(我没有看到异常,可能是因为我们的代码中甚至不支持异常)。

代码看起来不正确,但我找不到这个问题的正确解决方案,我尝试了很多版本,但都没有奏效。
我认为强制转换的智能指针对象的生命周期存在问题。

如何让它发挥作用?

解决方法

std::shared_ptr<firstCaseType>(static_cast<firstCaseType*>(command.context.get()))

这会从 context 的所有权网络中提取一个非拥有的原始指针,并将其传递给一个新的 std::shared_ptr,就好像它拥有它一样。解决方法是使用std::shared_ptr的别名构造函数(overload #8 here):

std::shared_ptr<firstCaseType>(command.context,static_cast<firstCaseType*>(command.context.get()))
//                             ^^^^^^^^^^^^^^^

,

代码肯定是错误的。您最终有两个共享指针管理相同的底层原始指针。您需要的是共享 ptr 的别名版本(请参见下面的完整示例):

#include <memory>

struct Foo { };

struct Boo : Foo { };

void g(std::shared_ptr<Foo> f)
{
    std::shared_ptr<Boo> p(f,static_cast<Boo*>(f.get()));
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。