对同一(原始)类型的static_cast是否产生任何代码?

Rob*_*ner 6 c++ casting

我想这都是在标题中说的......

但这是一个例子.特定

void functionThatTakesAFloat(float par);
float f = 3.5f;
Run Code Online (Sandbox Code Playgroud)

functionThatTakesAFloat(static_cast<float>(f));
Run Code Online (Sandbox Code Playgroud)

比较产生任何附加代码

functionThatTakesAFloat(f);
Run Code Online (Sandbox Code Playgroud)

或者static_cast编译器是否完全消除了这种情况?

编辑:我正在使用VC++(2010)

Ton*_*roy 10

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...>
Run Code Online (Sandbox Code Playgroud)

所以给出:

float my_float = ...;
Run Code Online (Sandbox Code Playgroud)

...这个...

f(static_cast<float>(my_float));
Run Code Online (Sandbox Code Playgroud)

......必须等同于......

float temp = my_float;
f(temp);
Run Code Online (Sandbox Code Playgroud)

它是否实际上遵循字面意义,并在非优化构建中生成临时值,将取决于编译器.如果你不相信你的优化器删除它(如果它曾被插入),那么你应该尝试另一个编译器...... ;-).


Ken*_*kot 6

这里的简单答案是,根据定义,来自floatto 的演员float是无操作.没有可想象的代码值得为这个演员阵容发光.在这种情况下,这个Universe中的某些编译器可能会发出毫无疑问的冗余代码,但可以安全地假设您永远不会遇到这样的编译器.