Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

visual c++ - What is the performance implication of converting to bool in C++?

[This question is related to but not the same as this one.]

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

This is with Visual C++ 2008 but I suspect other compilers may have similar warnings.

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's explanation of their warning is not particularly helpful. They imply that there is a good reason but they don't explain it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I was puzzled by this behaviour, until I found this link:

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

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.

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...