Search code examples
c++matrixmoveoperator-keywordmemory-efficient

Is it possible to implement move operator+/operator-/operator* for class of Matrix?


I am thinking on how can i define a class of real matrices NxN with the operations Add (Subtract) and Multiply. I am looking for Efficient Memory Usage.

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&);

Solution

  • Yes you can have additional overloads

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

    To reuse memory of one of the temporary.

    They can all be implemented with Matrix& operator += (Matrix&, const Matrix&) by changing the order as + is symmetrical. operator - would require dedicated code.

    Another way to optimize memory is to use expression templates instead of computing directly the result.

    It has its drawback about lifetime issue (especially with auto) though.