我正在实现一个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
返回 aexpr&
,但我不太确定。我认为std::move(lhs) -= rhs
会工作,但... - 如果它执行与-qualified 版本
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;