Search code examples
c++shared-ptrsmart-pointersdowncast

How to downcast shared_ptr without std::static_pointer_cast in C++?


we use EASTL and I can't use std::static_pointer_cast.
I receive a pointer to base class in my function and don't know, how to correctly cast it:

    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;
    }

The code above compiles, but throws some exception in the end of firstCaseFunction/secondCaseFunction (I don't see the exception, probably because we don't even support exceptions in our code).

The code doesn't look correct, but I can't find correct solution for this problem and I tried many versions, but none of them worked.
I think there is a problem with lifetime of the casted smart pointer objects.

How to make it work?


Solution

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

    This extracts a non-owning raw pointer from context's ownership network, and passes it to a new std::shared_ptr as if it were owning. The solution is to use std::shared_ptr's aliasing constructor (overload #8 here):

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