【问题标题】:How to downcast shared_ptr without std::static_pointer_cast in C++?如何在 C++ 中不使用 std::static_pointer_cast 向下转换 shared_ptr?
【发布时间】:2021-05-10 15:48:59
【问题描述】:

我们使用 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的末尾抛出了一些异常(我没有看到异常,可能是因为我们的代码甚至不支持异常)。

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

如何让它发挥作用?

【问题讨论】:

    标签: c++ shared-ptr smart-pointers downcast


    【解决方案1】:
    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()))
    //                             ^^^^^^^^^^^^^^^
    
    

    【讨论】:

    • 是的,就是这样!我找不到它,也不知道它叫什么。
    • 并将其包装在一个函数中,totally_not_std::static_pointer_cast
    【解决方案2】:

    代码肯定是错误的。您最终拥有两个共享指针来管理相同的底层原始指针。您需要的是 aliasing 版本的共享 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()));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-09
      • 1970-01-01
      • 2010-11-24
      • 2019-10-20
      • 2011-09-13
      • 2017-08-06
      相关资源
      最近更新 更多