typeID检查有效后,使用reinterpret_cast

Is using reinterpret_cast after typeid check valid?

本文关键字:reinterpret cast 使用 检查 有效 typeID      更新时间:2023-10-16

如果我首先验证了基本类的指针是某种类型的指针(使用typeid),那么在其上执行reinterpret_cast以节省某些性能是否有效?

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

和以后的某个地方:

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

据我所知,此代码正如我认为的那样正常运行。但是,我很好奇是否仅仅是因为我很幸运,还是实际上定义很好的用法和所有用法?以这种方式使用reinterpret_cast

,在您说仅使用普通多态性之前,我无法更改类,所以我需要以这种方式围绕它进行构建。

no,行为仍然是不确定的。

以这种方式使用reinterpret_cast仍然会破坏严格的混叠规则。

如果性能真的是这里的问题,那么您很可能想完全避免virtual类。

与bathsheba答案一样,您仍然具有不确定的行为。

但是,如果您没有虚拟继承,则可以使用static_cast,它将正确地将指针正确地取代到子类:

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