本文介绍了C++ 什么时候我们应该更喜欢使用两个链接的 static_cast 而不是 reinterpret_cast的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,这不是 为什么我们要在 C++ 中使用 reinterpret_cast,而两个链接的 static_cast 可以完成它的工作?.

我知道我们甚至不能使用两个链接的 static_cast 来实现这一点的情况,reinterpret_cast 可以做什么.但是在任何情况下,我应该更喜欢两个链接的 static_cast 而不是简单且更具可读性的 reinterpret_cast?

I know situations where we cannot use even two chained static_cast to achieve that, what reinterpret_cast does. But is there any situation where I should prefer a two chained static_cast over a simple and more readable reinterpret_cast?

推荐答案

reinterpret_cast 应该是一个巨大的闪烁符号,表示这看起来很疯狂,但我知道我在做什么.不要因为懒惰而使用它.

reinterpret_cast should be a huge flashing symbol that says THIS LOOKS CRAZY BUT I KNOW WHAT I'M DOING. Don't use it just out of laziness.

reinterpret_cast 表示将这些位视为……" 链式静态转换相同,因为它们可能会根据继承晶格修改其目标.

reinterpret_cast means "treat these bits as ..." Chained static casts are not the same because they may modify their targets according to the inheritence lattice.

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 或引发失败.

If you are not 100% sure that a points to a b, use dynamic_cast which will search for the above solution (albeit with a runtime cost). Bear in mind that this may return NULL or throw on failure.

我在回想我实际使用过reinterpret_cast的次数,实际上只有两个:

I'm trying to think of times when I've actually used reinterpret_cast, there are really only two:

  • 当一个函数正在压缩/加密任意缓冲区时,我想使用 const char * 来遍历它
  • if(*reinterpret_cast<uint32_t*>(array_of_4_bytes_A) < *reinterpret_cast<uint32_t*>(array_of_4_bytes_B) 或诸如此类.像这样的行会引起审查和评论.
  • when a function is zipping/encrypting an arbitrary buffer and I want to use a const char * to traverse it
  • if(*reinterpret_cast<uint32_t*>(array_of_4_bytes_A) < *reinterpret_cast<uint32_t*>(array_of_4_bytes_B) or somesuch. Lines like this invite scrutiny and demand comments.

否则,如果您有一个 A* 实际上是一个 B*,那么您可能需要一个联合.

Otherwise if you have a A* which is really a B* then you probably want a union.

这篇关于C++ 什么时候我们应该更喜欢使用两个链接的 static_cast 而不是 reinterpret_cast的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 07:46