Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 对相同(基元)类型的静态_转换是否产生任何代码?_C++_Casting - Fatal编程技术网

C++ 对相同(基元)类型的静态_转换是否产生任何代码?

C++ 对相同(基元)类型的静态_转换是否产生任何代码?,c++,casting,C++,Casting,我想这都是在标题里说的 但这里有一个例子。给定 void functionThatTakesAFloat(float par); float f = 3.5f; 做 或者编译器是否完全消除了这一静态\u cast 编辑: 我使用的是VC++(2010)理想情况下,编译器不应该为任何强制转换操作生成额外的代码(除了动态强制转换)特别是对于这样的原始类型。这里的简单答案是,根据定义,从float到float的转换是不可操作的。没有任何可以想象的代码值得为此转换发出。在这种情况下,这个世界中的某些编

我想这都是在标题里说的

但这里有一个例子。给定

void functionThatTakesAFloat(float par);
float f = 3.5f;

或者编译器是否完全消除了这一
静态\u cast

编辑:
我使用的是VC++(2010)

理想情况下,编译器不应该为任何强制转换操作生成额外的代码(除了
动态强制转换
)特别是对于这样的原始类型。

这里的简单答案是,根据定义,从
float
float
的转换是不可操作的。没有任何可以想象的代码值得为此转换发出。在这种情况下,这个世界中的某些编译器无疑会发出冗余代码,这可能是真的,但可以肯定的是,您永远不会遇到这样的编译器。

5.2.9/

-2- An expression e can be explicitly converted to a type T
    using a static_cast of the form static_cast<T>(e) if the
    declaration ``"T t(e);"'' is well-formed, for some invented
    temporary variable t (dcl.init). The effect of such an explicit
    conversion is the same as performing the declaration and
    initialization and then using the temporary variable as the
    result of the conversion. <cont...>
……这

f(static_cast<float>(my_float));

它是否真的遵循字面意思,并在未优化的构建中生成临时值,将取决于编译器。如果您不相信您的优化程序会删除它(如果它曾经被插入),那么您应该尝试另一个编译器…;-)

哇,有人想关闭这个“太本地化”。我不确定我会同意。这实际上是一个非常有趣的问题,尽管OP指定他想知道的编译器会让它受益。@JonathanSterling:我认为它太本地化了,因为它取决于编译器选项、编译器和可能的平台。问题中没有给出。但是例如,从float到int的静态_转换呢?我想这项工作需要一些汇编指令。reinterpret_cast是唯一一种我看不出有必要产生额外代码的类型转换。@Robert Hegner:reinterpret_cast在两种不同类型之间的
reinterpret_cast
有一种未指定的行为(也就是说,它取决于编译器/实现),它可能会更改指针地址,因此即使在那里,我会小心的。@ereOn:真有趣!罗伯特·海格纳:在什么情况下,重新解释施法会改变指针地址?嗯,我从来没有观察到过,但标准上说这是可能发生的。使用
reinterpret\u cast
的唯一保证是,如果将
a
类型的变量强制转换为a
B
,然后再次转换为a
a
,则会得到原始指针。没别的了。
-2- An expression e can be explicitly converted to a type T
    using a static_cast of the form static_cast<T>(e) if the
    declaration ``"T t(e);"'' is well-formed, for some invented
    temporary variable t (dcl.init). The effect of such an explicit
    conversion is the same as performing the declaration and
    initialization and then using the temporary variable as the
    result of the conversion. <cont...>
float my_float = ...;
f(static_cast<float>(my_float));
float temp = my_float;
f(temp);