Reinterpret_cast 与 C 风格的转换

2021-12-31 00:00:00 casting c++

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

I hear that reinterpret_cast is implementation defined, but I don't know what this really means. Can you provide an example of how it can go wrong, and it goes wrong, is it better to use C-Style cast?

推荐答案

C 风格的转换并不好.

The C-style cast isn't better.

它只是按顺序尝试各种 C++ 风格的类型转换,直到找到一个有效的类型.这意味着当它像 reinterpret_cast 一样运行时,它会遇到与 reinterpret_cast 完全相同的问题.但除此之外,它还有这些问题:

It simply tries the various C++-style casts in order, until it finds one that works. That means that when it acts like a reinterpret_cast, it has the exact same problems as a reinterpret_cast. But in addition, it has these problems:

  • 它可以做很多不同的事情,并且通过阅读代码并不总是清楚将调用哪种类型的转换(它的行为可能类似于 reinterpret_castconst_caststatic_cast,它们做的事情非常不同)
  • 因此,更改周围的代码可能会改变演员表的行为
  • 阅读或搜索代码时很难找到 - reinterpret_cast 很容易找到,这很好,因为 casts 很丑陋,使用时应注意.相反,通过搜索可靠地找到 C 风格的类型转换(如 (int)42.0)要困难得多
  • It can do many different things, and it's not always clear from reading the code which type of cast will be invoked (it might behave like a reinterpret_cast, a const_cast or a static_cast, and those do very different things)
  • Consequently, changing the surrounding code might change the behaviour of the cast
  • It's hard to find when reading or searching the code - reinterpret_cast is easy to find, which is good, because casts are ugly and should be paid attention to when used. Conversely, a C-style cast (as in (int)42.0) is much harder to find reliably by searching

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

To answer the other part of your question, yes, reinterpret_cast is implementation-defined. This means that when you use it to convert from, say, an int* to a float*, then you have no guarantee that the resulting pointer will point to the same address. That part is implementation-defined. But if you take the resulting float* and reinterpret_cast it back into an int*, then you will get the original pointer. That part is guaranteed.

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

But again, remember that this is true whether you use reinterpret_cast or a C-style cast:

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

相关文章