c++ - Reinterpret_cast 与 C 风格的类型转换

标签 c++ casting

我听说 reinterpret_cast 是实现定义的,但我不知道这真正意味着什么。你能提供一个例子说明它是如何出错的,它出错了,使用 C-Style cast 更好吗?

最佳答案

C 风格的类型转换并不好。

它只是按顺序尝试各种 C++ 风格的强制转换,直到找到一个可行的。这意味着当它像 reinterpret_cast 一样工作时,它与 reinterpret_cast 有完全相同的问题。但除此之外,它还有这些问题:

  • 它可以做很多不同的事情,并且从阅读代码中并不总是清楚将调用哪种类型的转换(它的行为可能类似于 reinterpret_castconst_caststatic_cast,它们做的事情完全不同)
  • 因此,更改周围的代码可能会改变强制转换的行为
  • 阅读或搜索代码时很难找到 - reinterpret_cast 很容易找到,这很好,因为强制转换很难看,使用时要注意。相反,通过搜索可靠地找到 C 风格的转换(如 (int)42.0)要困难得多

要回答您问题的另一部分,是的,reinterpret_cast 是实现定义的。这意味着当您使用它从 int* 转换为 float* 时,您无法保证生成的指针将指向相同的地址.那部分是实现定义的。但是,如果您将生成的 float*reinterpret_cast 返回到 int*,那么您将获得原始指针。这部分是有保证的。

但请记住,无论您使用 reinterpret_cast 还是 C 风格的转换,这都是正确的:

int i;
int* p0 = &i;

float* p1 = (float*)p0; // implementation-defined result
float* p2 = reinterpret_cast<float*>(p0); // implementation-defined result

int* p3 = (int*)p1; // guaranteed that p3 == p0
int* p4 = (int*)p2; // guaranteed that p4 == p0
int* p5 = reinterpret_cast<int*>(p1); // guaranteed that p5 == p0
int* p6 = reinterpret_cast<int*>(p2); // guaranteed that p6 == p0

关于c++ - Reinterpret_cast 与 C 风格的类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7831696/

相关文章:

具有可选属性的 C++ 类

c++ - 用于稀疏酉矩阵的最佳 C++ 矩阵库

返回中的 C++ 类型转换优先级

java - 为什么会收到 ClassCastException 以及如何修复它?

java - 如何将对象作为可比参数发送给方法?

c++ - 在源代码中使用 C++ 库的 CMakeLists

c++ - 在丰富的编辑文本控件中检测换行符

C# COM 服务器 - 在 C++ 中测试

java - 如何判断向下转型在 Java 中是否合法?

c++ - 使用 STL 容器时应该使用 int 还是 unsigned int?