为什么默认运算符 <=> 为我们免费提供运算符 == 而自定义实现则不然? [重复]

问题描述 投票:0回答:1

我尝试了两种定义

operator<=>
的变体, 变体 A 使用
= default
。因此我可以使用
operator ==
。 但如果我在变体 B 中手动实现
operator<=>
,则比较
x1 == x2
将停止工作。

为什么会这样? C++20 标准中是这么规定的吗?到目前为止我找不到任何解释。

对我来说

operator<=>
是一个函数,无论是否默认。我预计 A 和 B 之间没有区别。

代码:

#include <iostream>

class X {
public:
    int y;

/*A*/    inline std::strong_ordering operator<=>(const X& another) const = default;    
/*B*/    //inline std::strong_ordering operator<=>(const X& another) const { return y <=> another.y; }
};

int main()
{
    using std::cout;
    using std::endl;
    
    X x1;
    x1.y = 5;
    
    X x2;
    x2.y = 7;
    
    cout << "x1 == x2:   " << (x1 == x2) << endl;
    cout << "x1 == x2:   " << (x1 <=> x2 == 0) << endl;

    return 0;
}
c++ c++20
1个回答
1
投票

在 C++20 中,operator<=>(宇宙飞船运算符)的行为确实可能略有不同,具体取决于它是默认实现还是手动实现。这种差异源于默认运算符<=>与默认运算符==的交互方式。

当您使用默认版本(=默认)时,编译器会为您生成operator<=>和operator==。生成的运算符==使用运算符<=>来执行相等比较。这是 C++20 标准中指定的。

另一方面,当你手动实现operator<=>时,编译器不会自动为你生成operator==。这意味着如果您需要operator==才能工作,您还必须显式定义它。

© www.soinside.com 2019 - 2024. All rights reserved.