我尝试在一个包含这样的引用成员的简单类中默认操作符==和操作符<=>:
#include <iostream>
#include <string>
class Simple
{
public:
Simple(const std::string& data)
: data_(data)
{
}
auto operator<=>(const Simple&) const = default;
private:
const std::string& data_;
};
int main(int argc, char** argv)
{
std::string str1 = "one";
Simple s1(str1);
std::string str2 = "two";
Simple s2(str2);
std::cout << (s1 < s2) << std::endl; // compiler error
return 0;
}
clang 编译器指出
warning: explicitly defaulted three-way comparison operator is implicitly deleted
note: defaulted 'operator<=>' is implicitly deleted because class 'Simple' has a reference member
我没有收到其他编译器(例如 MSVC)的警告,但是当我尝试使用它时,我收到编译错误:
<source>(62): error C2280: 'auto Simple::operator <=>(const Simple &) const': attempting to reference a deleted function
<source>(49): note: see declaration of 'Simple::operator <=>'
<source>(49): note: 'auto Simple::operator <=>(const Simple &) const': function was implicitly deleted because 'Simple' data member 'Simple::data_' of type 'const std::string &' is a reference type
<source>(52): note: see declaration of 'Simple::data_'
其他默认功能(例如复制分配)当然会被删除,因为它们对于引用成员来说是不可能的。
但是为什么参考点的内容不能自动比较呢?
手动实现它的最短方法是什么?
引用成员确实阻止编译器生成默认的三向比较运算符。
您可以通过以下方式手动实现:
auto operator<=>(const Simple& other) const
{
return data_ == other.data_ ? std::strong_ordering::equal :
data_ < other.data_ ? std::strong_ordering::less :
std::strong_ordering::greater;
}