实现高效的算术运算符

Hol*_*olt 5 c++

我正在实现一个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)
}
Run Code Online (Sandbox Code Playgroud)

以下是一些相关的问题:

  1. 这是正确的实施方式吗operator-()?有更惯用的方法吗?
  2. (A),我需要吗std::move?我认为是这样,因为lhs -= rhs返回 a expr&,但我不太确定。我认为std::move(lhs) -= rhs会起作用,但是...
  3. 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;
Run Code Online (Sandbox Code Playgroud)