在typeid检查有效后使用reinterpret_cast吗?

时间:2017-12-06 15:53:54

标签: c++ c++11 visual-c++ visual-studio-2012

如果我首先验证指向基类的指针属于某种类型(使用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

在你说只使用正常的多态性之前,我无法改变类,因此我需要围绕它构建这种方式。

2 个答案:

答案 0 :(得分:1)

不,这种行为仍然会被正式定义。

以这种方式使用reinterpret_cast仍会违反严格的别名规则。

如果性能确实是一个问题,那么您可能希望完全避免virtual个类。

答案 1 :(得分:1)

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