我尝试在包含如下引用成员的简单类中将operator==
和默认为:operator<=>
#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_'
其他默认功能(如复制分配)当然也会被删除,因为它们无法通过引用成员实现。
但为什么引用指向的内容不能自动进行比较呢?
并且手动实现它的最短方法是什么?