5

我正在实现一个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)
}

以下是一些相关的问题:

  1. 这是正确的实施方式operator-()吗?有没有更惯用的方式这样做?
  2. (A),我需要std::move吗?我认为是因为lhs -= rhs返回 a expr&,但我不太确定。我认为std::move(lhs) -= rhs会工作,但...
  3. 如果它执行与-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;
4

0 回答 0