gpt4 book ai didi

c++ - 对相同(原始)类型的 static_cast 会产生任何代码吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:07:40 25 4
gpt4 key购买 nike

我想这一切都在标题中说了...

但这是一个例子。给定

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

functionThatTakesAFloat(static_cast<float>(f));

相比产生任何额外的代码
functionThatTakesAFloat(f);

或者这个 static_cast 是否被编译器完全消除了?

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

最佳答案

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...>

因此给定:

float my_float = ...;

……这……

f(static_cast<float>(my_float));

...必须等价于...

float temp = my_float;
f(temp);

它是否真的按照字面意思,并在非优化构建中生成一个临时文件,将取决于编译器。如果您不相信您的优化器会删除它(如果它曾被插入),那么您应该尝试另一个编译器...;-)。

关于c++ - 对相同(原始)类型的 static_cast 会产生任何代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5814406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com