0

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?

Lukas Salich
  • 959
  • 2
  • 12
  • 30

2 Answers2

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

Quentin
  • 62,093
  • 7
  • 131
  • 191
1

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()));
}
SergeyA
  • 61,605
  • 5
  • 78
  • 137