对于非指针类型,使用static_cast而不是C样式转换有什么优势吗? [英] Is there any advantage in using static_cast rather than C-style casting for non-pointer types?

查看:145
本文介绍了对于非指针类型,使用static_cast而不是C样式转换有什么优势吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很清楚使用 static_cast 而不是使用C风格的指针类型转换的优点。

I am well aware of the advantage in using static_cast rather than C-style casting for pointer types.

如果指针类型不兼容,则:

If the pointer types are incompatible, then:


  • static_cast 将产生一个编译结果源代码中特定行的时间错误

  • C样式转换可能导致程序执行中随机点的运行时错误

  • static_cast will yield a compile-time error at a specific line within the source code
  • C-style casting might lead to a runtime error at a "random" point in the execution of the program

但是我找不到非指针类型的任何类似示例。

But I am unable to find any similar example for non-pointer types.

,两种类型的转换方法对于非指针类型都产生相同的结果。

In other words, both casting methods yield the same result for non-pointer types.

是正确的,还是我错过了任何事情?

Is that correct, or have I missed anything?

如果可以, static_cast 是否仅用于非指针类型以保持编码一致性?

If yes, is static_cast used for non-pointer types only in order to maintain coding consistency?

推荐答案

其他两个答案尚未提及的一个优点是, static_cast 更容易发现。众所周知,括号的含义在C ++中已重载,因此很难发现邪恶的(甚至是错误的)强制类型转换。但是,当我看到以 _cast 结尾的内容时,就像是精神上的颠簸:我放慢脚步,仔细检查为什么类型系统被颠覆。

One advantage which the other two answers didn't mention yet is that static_cast is much easier to spot. The meaning of parentheses is notoriously overloaded in C++ and it can be difficult to spot evil (or even incorrect) casts. When I see something ending in _cast though, it's like a mental speed bump: I slow down and carefully check why the type system is being subverted.

这篇关于对于非指针类型,使用static_cast而不是C样式转换有什么优势吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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