我最近了解到成员函数可以是ref-qualified,这让我可以编写
struct S {
S& operator=(S const&) & // can only be used if the implicit object is an lvalue
{
return *this;
}
};
S operator+(S const &, S const &) {
return {};
}
从而阻止用户做类似的事情
S s{};
s + s = S{}; // error
但是,我看到那std::string
的成员operator=
不这样做。所以下面的代码编译没有警告
std::string s;
s + s = s;
有理由允许这样做吗?
如果没有,将来是否可以添加 ref 限定符,或者会以某种方式破坏现有代码?