三向比较运算符与减法有何不同? [英] How is the three-way comparison operator different from subtraction?

查看:178
本文介绍了三向比较运算符与减法有何不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++ 20中有一个新的比较运算符<=>.但是,我认为在大多数情况下,简单的减法效果很好:

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, const char *b) {
    while (*a == *b && *a != 0 && *b != 0) {
        a++, b++;
    }
    // Version 1
    return *a - *b;
    // Version 2
    return *a <=> *b;
    // Version 3
    return ((*a > *b) - (*a < *b));
}

它们具有相同的效果.我真的不明白其中的区别.

They have the same effect. I can't really understand the difference.

推荐答案

运算符解决了用减法得到的数值溢出的问题:如果从接近INT_MIN的负数中减去一个大的正数,则表示得到一个不能表示为int的数字​​,从而导致未定义的行为.

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.

尽管版本3摆脱了此问题,但它完全缺乏可读性:以前从未见过此技巧的人需要花一些时间来理解. <=>运算符也解决了可读性问题.

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.

这只是新操作员解决的一个问题. Herb Sutter的持续比较 paper 讨论了<=>与该语言的其他数据类型一起使用时,减法可能会导致不一致的结果.

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.

这篇关于三向比较运算符与减法有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆