首页 > 解决方案 > 是否可以为 Matrix 类实现 move operator+/operator-/operator*?

问题描述

我正在考虑如何使用 Add(Subtract)和 Multiply 操作定义一类实矩阵 NxN。我正在寻找有效的内存使用。

class Matrix {
private:
    std::size_t _size_n;
    double **_pMatrix;

public:
    Matrix(const size_t n);

    ~Matrix();

    double &operator()(size_t, const size_t);

    double operator()(size_t, const size_t) const;

    size_t size_n() const { return _size_n; }
};

std::ostream &operator<<(std::ostream &, const Matrix &);

Matrix operator+(const Matrix&, const Matrix&);
Matrix operator-(const Matrix&, const Matrix&);
Matrix operator*(const Matrix&, const Matrix&);

标签: c++matrixmoveoperator-keywordmemory-efficient

解决方案


是的,你可以有额外的重载

Matrix/*&&*/ operator+(const Matrix&, Matrix&&);
Matrix/*&&*/ operator+(Matrix&&, const Matrix&);
Matrix/*&&*/ operator+(Matrix&&, Matrix&&);

重用临时内存之一。

它们都可以Matrix& operator += (Matrix&, const Matrix&) 通过更改顺序来实现,因为 + 是对称的。operator -将需要专用代码。

另一种优化内存的方法是使用表达式模板而不是直接计算结果。

不过,它在生命周期问题(尤其是auto)方面有其缺点。


推荐阅读