首先,这不是 Why do we have reinterpret_cast in C++ when two chained static_cast can do it's job? 的拷贝.
我知道我们甚至不能使用两个链式 static_cast
来实现的情况,reinterpret_cast
所做的。但是在任何情况下我应该更喜欢两个链接的 static_cast
而不是简单且更具可读性的 reinterpret_cast
?
最佳答案
reinterpret_cast
应该是一个巨大的闪烁符号,表示这看起来很疯狂,但我知道我在做什么。不要因为懒惰而使用它。
reinterpret_cast
意思是“将这些位视为……”链式静态转换不是相同的,因为它们可能会根据继承网格修改其目标。
struct A {
int x;
};
struct B {
int y;
};
struct C : A, B {
int z;
};
C c;
A * a = &c;
int main () {
assert (reinterpret_cast <B *> (a) != static_cast <B *> (static_cast <C *> (a)));
}
如果您不是 100% 确定 a
指向 b
, 使用 dynamic_cast
它将搜索上述解决方案(尽管有运行时成本)。请记住,这可能会返回 NULL 或引发失败。
我正在努力回想我实际使用过 reinterpret_cast
的时间,实际上只有两个:
- 当函数正在压缩/加密任意缓冲区并且我想使用
const char *
时遍历它 -
if(*reinterpret_cast<uint32_t*>(array_of_4_bytes_A) < *reinterpret_cast<uint32_t*>(array_of_4_bytes_B)
或类似的。像这样的行会引起审查并征求意见。
否则如果你有一个 A*
这实际上是一个 B*
那么您可能想要一个 union 。
关于C++我们什么时候应该更喜欢使用两个链接的static_cast而不是reinterpret_cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6594395/