How is the three-way comparison operator different from subtraction?

后端 未结 3 966
忘了有多久
忘了有多久 2021-01-31 01:35

There\'s a new comparison operator <=> in C++20. However I think in most cases a simple subtraction works well:

int my_strcmp(const char *a, c         


        
3条回答
  •  孤城傲影
    2021-01-31 02:10

    The operator solves the problem with numeric overflow that you get with subtraction: if you subtract a large positive number from a negative that is close to INT_MIN, you get a number that cannot be represented as an int, thus causing undefined behavior.

    Although version 3 is free from this problem, it utterly lacks readability: it would take some time to understand by someone who has never seen this trick before. <=> operator fixes the readability problem, too.

    This is only one problem addressed by the new operator. Section 2.2.3 of Herb Sutter's Consistent comparison paper talks about the use of <=> with other data types of the language where subtraction may produce inconsistent results.

提交回复
热议问题