【发布时间】:2020-04-10 14:01:11
【问题描述】:
我最近learned说成员函数可以是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= does not do this。所以下面的代码编译没有警告
std::string s;
s + s = s;
有允许这样做的理由吗?
如果没有,将来是否可以添加 ref 限定符,或者会以某种方式破坏现有代码?
【问题讨论】:
-
@cigien 为什么不应该这个操作 s + s = s;允许吗?
-
@VladfromMoscow 据我所知,它没有做任何有用的事情。
-
考虑例如 std::cout
-
@VladfromMoscow 他们可以写
std::cout << ( s + s + 'a' );。不确定我是否认为这是一个令人信服的理由。 -
@VladfromMoscow:
+=和=是不同的运算符。这个问题特别是关于operator=,它会覆盖字符串。因此,没有有用的纯右值 lhs 版本不等同于仅从=操作数创建纯右值。
标签: c++ operator-overloading stdstring ref-qualifier