实现高效的算术运算符

时间:2020-10-20 09:53:44

标签: 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)
}

以下是一些相关的问题:

  1. 实现operator-()的正确方法吗?有更多惯用的方式吗?
  2. (A)中,我是否需要std::move?我认为是因为lhs -= rhs返回了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;

0 个答案:

没有答案
相关问题