gpt4 book ai didi

c++ - 在 C++ 中转换为 bool 对性能有何影响?

转载 作者:IT老高 更新时间:2023-10-28 14:00:00 27 4
gpt4 key购买 nike

[此问题与this one 相关但不相同。 .]

我的编译器警告将某些类型隐式转换或强制转换为 bool,而显式转换不会产生警告:

long t = 0;
bool b = false;
b = t; // performance warning: forcing long to bool
b = (bool)t; // performance warning
b = bool(t); // performance warning
b = static_cast<bool>(t); // performance warning
b = t ? true : false; // ok, no warning
b = t != 0; // ok
b = !!t; // ok

这是 Visual C++ 2008,但我怀疑其他编译器可能有类似的警告。

所以我的问题是:转换/转换为 bool 的性能影响是什么?在某些情况下(例如,对于某些目标架构或处理器),显式转换是否具有更好的性能?隐式转换是否会以某种方式混淆优化器?

微软的 explanation他们的警告并不是特别有用。他们暗示有一个很好的理由,但他们没有解释。

最佳答案

我对这种行为感到困惑,直到我找到了这个链接:

http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=99633

显然,来自“拥有”此警告的 Microsoft 开发人员:

This warning is surprisingly helpful, and found a bug in my code just yesterday. I think Martin is taking "performance warning" out of context.

It's not about the generated code, it's about whether or not the programmer has signalled an intent to change a value from int to bool. There is a penalty for that, and the user has the choice to use "int" instead of "bool" consistently (or more likely vice versa) to avoid the "boolifying" codegen. [...]

It is an old warning, and may have outlived its purpose, but it's behaving as designed here.

所以在我看来,警告更多的是关于风格和避免一些错误。

希望这能回答你的问题...

:-p

关于c++ - 在 C++ 中转换为 bool 对性能有何影响?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/206564/

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