mercredi 6 décembre 2017

Is using reinterpret_cast after typeid check valid?

If I verify first that pointer to base class is of some type (using typeid), is it valid to do reinterpret_cast on it to save some performance?

class Base {
    virtual ~Base() {}
};
class A : Base {};
class B : Base {};
...
class Z : Base {};

and later on somewhere:

void fn(Base & msg) {
    const auto & tid = typeid(msg);
    if (tid == typeid(A)) {
        A * ptr = reinterpret_cast<A*>(&msg);
    } else if (tid == typeid(B)) {
        B * ptr = reinterpret_cast<B*>(&msg);
    } ...
    ...
    } else if (tid == typeid(Z)) {
        Z * ptr = reinterpret_cast<Z*>(&msg);
    }
}

As far as I can tell, this code works fine as I think it should. However, I'm curious if it's just because I'm lucky or is this actually well defined usage and all? Using reinterpret_cast this way.

And before you say to just use normal polymorphism for this, I'm not able to change classes as they are so I need to build this way around it.

Aucun commentaire:

Enregistrer un commentaire