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

时间:2021-05-10 15:48:59

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

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

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

如何让它发挥作用?

2 个答案:

答案 0 :(得分:3)

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()))
//                             ^^^^^^^^^^^^^^^

答案 1 :(得分:1)

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