static_cast (foo)vs.(int)foo

问题描述:

难道有人请详细说明不同之处吗?static_cast <int>(foo)vs.(int)foo

+1

确切副本http://*.com/questions/103512/in-c-why-use-staticcastintx-instead-of-intx – jalf 2009-01-24 10:11:27

+0

感谢您的链接,贾尔夫。 – 2009-01-24 10:14:43

区别在于(int)foo可以表示六种不同的事物。 它可能是static_cast(在静态已知类型之间转换),它可能是const_cast(添加或删除常量),或者它可能是reinterpret_cast(在指针类型之间转换)

编译器尝试每个直到它找到一个有效的工作。这意味着它可能并不总是选择你期望的,所以它可能会成为一个微妙的错误来源。

此外,static_cast更容易搜索或搜索/替换。

(int)foo与C++ reinterpret_cast<int>比较最多,即对演员表的有效性没有检查。

+0

http://www.velocityreviews.com/forums/t280611-reinterpretcastltgt-v-staticcastltgt.html扩展了static_cast和reinterpret_cast之间的区别 – 2009-01-24 10:14:23

看什么Stroustrup has to say about that,包括以下内容:

因为C风格的类型转换(T)可以用来表达许多逻辑上不同的操作,则编译器只赶上滥用最起码的机会。 [...]

引入了“新风格”,让程序员有机会更清楚地陈述他们的意图,并让编译器捕捉更多错误。 [...]

特别是,C++这种区别static_cast之间reinterpret_cast

的想法是,通过允许的static_cast转换有点不太可能导致比那些需要reinterpret_cast的错误。原则上,可以使用static_cast的结果而不将其重新转换为原始类型,而在使用reinterpret_cast的结果以确保可移植性之前,您应该始终将reinterpret_cast的结果转换回原始类型。