typeID检查有效后,使用reinterpret_cast
Is using reinterpret_cast after typeid check valid?
如果我首先验证了基本类的指针是某种类型的指针(使用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);
}
}
相关文章:
- 如何理解C++标准N3337中的expr.const.cast子句8
- C++Cast运算符过载
- 错误:"cast"未命名类型void setCastDescription(std::string
- 通过使用 const-cast 的非常量引用来延长临时的寿命
- "(void) cast"与功能有什么区别 "__attributes__"来沉默未使用的参数警告?
- C++:"Expected '(' for function-style cast or type construction"错误
- 为什么选择 g++ 给予者:"error: cast to pointer from integer of different size [-Werror=int-to-pointer-cast]"
- Gtk+ g_signal_connect() 和 C++ lambda 会导致"invalid cast"错误
- Shared_ptr cast vs static_cast speed
- C++20 中的严格别名规则是否允许标准 c++ unicode 字符和下划线类型之间"reinterpret
- 在 iOS 上使用 Aruco 构建 OpenCV 时"Functional-style cast from id to double is not allowed"
- 覆盖 CAST 运算符(我认为它被称为向下转换)
- C++错误,隐 <function-style-cast> 式要求使用模板化类一次调用多个构造函数的多个转换
- 如何修复<function-style-cast>错误:无法从'initializer list'转换为asdending比较<W>(模板函子)
- C++ C++ 中的函数声明,键入 CAST
- static_cast会丢弃错误,但C风格的演员cast有效
- C++ cast char * to unsigned char
- 禁用 Clang 中的"cast from pointer to smaller type uint32_t"错误
- 是否可以使用gcc 3.3版修复与int*cast相关的Sun Solaris OS 5.8分段故障
- C++ const-cast 一个引用