C++我们什么时候应该更喜欢使用两个链接的static_cast而不是reinterpret_cast

标签 c++ casting reinterpret-cast static-cast

首先,这不是 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/

相关文章:

c++ - 使用reinterpret_cast作为成员函数参数

c++ - 执行变量原始拷贝的简单转换是否会破坏严格的别名?

C++ 禁止从 const char* 设置 char* 和 char[]

c++ - 如何在 Windows 上使用 Visual Studio Code 在 Docker 中编译/调试 C++ 应用程序

c++ - 将 8 位 PCM 转换为 16 位 PCM

vb.net - 在 Visual Basic 中类型转换?

c++ - 我可以使用 reinterpret_cast 将指向成员函数的指针转换为 char 数组并返回吗?

c++ - 尽管已初始化变量,编译器仍给出未初始化的局部变量错误

c# - 将 Excel 导入 ASP.NET 时的 OleDbDataAdapter 和列转换

sql-server - MSSQL 聚合忽略 where 子句