C样式的强制转换与函数样式的强制转换相同吗? [英] Is a C-style cast identical to a function-style cast?
问题描述
从
函数样式案例与C样式强制转换有何不同?或者,如果它们相同,是否是Resharper中的bug,它也应该发出警告? int(d)
使用安全吗?它看起来比建议的 static_cast< int>(d);
.
我没有标准的引号,但是cppreference通常就足够了.
函数强制转换表达式由一个简单的类型说明符或一个typedef说明符组成(换句话说,一个单词类型名称:
unsigned int(expression)
或int *(expression)
无效),然后在括号中使用单个表达式.此强制转换表达式与相应的C样式强制转换表达式完全相同.
对于Resharper来说, C ++ cast 可能包含功能转换,因为仅在C ++中有效.
您在问题中链接的答案说明了功能强制转换的安全性.在您的情况下, int(d)
应该等效于 static_cast< int>(d)
.但通常来说,C样式或函数类型的转换是不安全的,因为它们在某些情况下可能等同于 reinterpret_cast
,例如(double *)some_int_ptr
.
From this answer to the question "When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?":
C-style cast and function-style cast are casts using
(type)object
ortype(object)
, respectively.
It then begins to list the behavior of the C-style cast, but never tells whether the function-style cast is identical or not.
I'm asking because Resharper for C++ warns me in case of C-style casts but does not warn me in case of function-style casts:
In what way is the the function-style case different from the C-style cast? Or, if they are identical, is it a bug in Resharper and it should emit a warning, too? Is int(d)
safe to use? It looks much simpler than the suggested static_cast<int>(d);
.
I don't have a quote from the standard, but cppreference is usually good enough.
The functional cast expression consists of a simple type specifier or a typedef specifier (in other words, a single-word type name:
unsigned int(expression)
orint*(expression)
are not valid), followed by a single expression in parentheses. This cast expression is exactly equivalent to the corresponding C-style cast expression.
As for Resharper, it's possible that to it C++ cast includes a functional cast, as that is only valid in C++.
The answer you linked in your question explains how safe a functional cast is. In your case int(d)
should be equivalent to static_cast<int>(d)
. But in general a C-style or functional cast are unsafe as they can be equivalent to reinterpret_cast
in certain situations, e.g. (double*)some_int_ptr
.
这篇关于C样式的强制转换与函数样式的强制转换相同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!