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

前端 未结 11 850
后悔当初
后悔当初 2020-12-03 02:36

[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

相关标签:
11条回答
  • 2020-12-03 03:01

    I don't think performance is the issue here. The reason you get a warning is that information is lost during conversion from int to bool.

    0 讨论(0)
  • 2020-12-03 03:07

    As far as I know, there is no warning on any other compiler for this. The only way I can think that this would cause a performance loss is that the compiler has to compare the entire integer to 0 and then assign the bool appropriately (unlike a conversion such as a char to bool, where the result can be copied over because a bool is one byte and so they are effectively the same), or an integral conversion which involves copying some or all of the source to the destination, possibly after a zero of the destination if it's bigger than the source (in terms of memory).

    It's yet another one of Microsoft's useless and unhelpful ideas as to what constitutes good code, and leads us to have to put up with stupid definitions like this:

    template <typename T>
    inline bool to_bool (const T& t)
      { return t ? true : false; }
    
    0 讨论(0)
  • 2020-12-03 03:07

    Based on your link to MS' explanation, it appears that if the value is merely 1 or 0, there is not performance hit, but if it's any other non-0 value that a comparison must be built at compile time?

    0 讨论(0)
  • 2020-12-03 03:12

    Unless you're writing code for a really critical inner loop (simulator core, ray-tracer, etc.) there is no point in worrying about any performance hits in this case. There are other more important things to worry about in your code (and other more significant performance traps lurking, I'm sure).

    0 讨论(0)
  • 2020-12-03 03:16

    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

    0 讨论(0)
提交回复
热议问题