我正在实现一个不便宜的expr
类,并且我想实现适当的“有效”算术运算符。为了解决这个问题,我将重点介绍operator-
。
class expr {
public:
expr(expr const&) = default;
expr(expr &&) = default;
expr operator-() const& { return -expr(*this); }
expr operator-() && {
// Perform operations in-place.
return std::move(*this);
}
expr& operator-=(expr const& other) & {
// In-place operations.
return *this;
}
expr&& operator-=(expr const& other) && {
// In-place operations.
return std::move(*this); // Do I really need this move?
}
};
expr operator-(expr const& lhs, expr const& rhs) {
return expr(lhs) -= rhs;
}
expr operator-(expr &&lhs, expr &&rhs) {
return std::move(lhs -= rhs); // (A)
}
以下是一些相关的问题:
operator-()
的正确方法吗?有更多惯用的方式吗?(A)
中,我是否需要std::move
?我认为是因为lhs -= rhs
返回了expr&
,但我不确定。我认为std::move(lhs) -= rhs
可以工作,但是... expr&& operator-=(expr const&) &&
与合格的&
版本执行相同的操作,我应该实现吗?不管有没有过载,以下代码将发生什么:expr e1;
// Is e2 copy-constructed or move-constructed if there is no operator-=() &&? And if there is?
auto e2 = expr() -= e1;