[这个问题与这个.]
我的编译器警告将某些类型隐式转换或强制转换为 bool 而显式转换不会产生警告:
My compiler warns about implicitly converting or casting certain types to bool whereas explicit conversions do not produce a warning:
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 但我怀疑其他编译器可能有类似的警告.
This is with Visual C++ 2008 but I suspect other compilers may have similar warnings.
所以我的问题是:强制转换/转换为 bool
的性能影响是什么?在某些情况下(例如,对于某些目标架构或处理器),显式转换是否具有更好的性能?隐式转换是否会以某种方式混淆优化器?
So my question is: what is the performance implication of casting/converting to bool
? Does explicit conversion have better performance in some circumstance (e.g., for certain target architectures or processors)? Does implicit conversion somehow confuse the optimizer?
Microsoft 对其警告的解释并不是特别有用.他们暗示有一个很好的理由,但他们没有解释.
Microsoft's explanation of their warning is not particularly helpful. They imply that there is a good reason but they don't explain it.
我对这种行为感到困惑,直到我找到了这个链接:
I was puzzled by this behaviour, until I found this link:
http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=99633
显然,来自拥有"此警告的 Microsoft 开发人员:
Apparently, coming from the Microsoft Developer who "owns" this warning:
这个警告令人惊讶有帮助,并在我的代码中发现了一个错误就在昨天.我认为马丁是去掉性能警告"上下文.
This warning is surprisingly helpful, and found a bug in my code just yesterday. I think Martin is taking "performance warning" out of context.
这与生成的代码无关,这是关于是否程序员已表示有意将值从 int 更改为 bool.对此有处罚,并且用户可以选择使用int"而不是始终如一地布尔"(或反之亦然)以避免布尔化"代码生成器.[...]
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. [...]
这是一个旧警告,可能有超过了它的目的,但它表现得像这里的设计.
所以在我看来,警告更多的是关于风格和避免一些错误.
So it seems to me the warning is more about style and avoiding some mistakes than anything else.
希望这能回答您的问题...
Hope this will answer your question...
:-p
这篇关于在 C++ 中转换为 bool 对性能有什么影响?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!