简体   繁体   中英

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?

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

The code is most certainly wrong. You end up having two shared pointers managing the same underlying raw pointer. What you need here is an aliasing version of shared ptr (see full example below):

#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()));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM