C ++我们什么时候应该使用一个两链的static_cast over reinterpret_cast [英] C++ When should we prefer to use a two chained static_cast over reinterpret_cast

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

问题描述

首先,这不是



我知道我们甚至不能使用两个链 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 * );
}

如果您不是100%确定 / code>指向 b ,使用 dynamic_cast ,它将搜索上述解决方案运行时成本)。请记住,这可能返回NULL或抛出失败。



我试图想到的时候,我实际使用 reinterpret_cast ,真的只有两个:




  • 当一个函数是压缩/加密任意缓冲区, a const char * 以遍历它

  • if(* reinterpret_cast< uint32_t *>(array_of_4_bytes_A)



否则,如果你有 A * 这真的是一个 B * ,那么你可能想要一个联合。 / p>

First of all, this is not a duplicate of Why do we have reinterpret_cast in C++ when two chained static_cast can do it's job?.

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 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 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)));
}

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.

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

  • 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.

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

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

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆