The + operator for matrices in C ++

I believe that a naive implementation of the + operator for matrices (e.g. 2D) in C ++ would be:

class Matrix {

  Matrix operator+ (const Matrix & other) const {
      Matrix result;
      // fill result with *this.data plus other.data
      return result;
  }
}

so that we can use it as

Matrix a;
Matrix b;
Matrix c;

c = a + b;

Right?

But if the matrices are large, this is inefficient, since we make one unnecessary copy (the result of the return).

Therefore, if we are not effective, we must forget the pure challenge:

c = a + b;

Right?

What would you suggest or prefer? Thank.

+5
source share
8 answers

++ , ( " ", NRVO). "RVO", , .

++ NRVO, RVO, , , , .

: , , , , . , const:

Matrix operator+(Matrix const &other) const { 
    Matrix result;
    // ...
    return result;
}

... else, , :

Matrix operator+(Matrix other) const { 
    other += *this;
    return other;
}

, (.. b+a a+b), , , .

+12

, , . , .

, - -, () .

, , , :

void add(Matrix & result, const Matrix & lhs, const Matrix & rhs) ;

( ), , + . +, + =:

Matrix & operator += (Matrix & result, const Matrix & rhs) ;
{
   // add rhs to result, and return result
   return result ;
}

Matrix operator + (const Matrix & lhs, const Matrix & rhs) ;
{
   Matrix result(lhs) ;
   result += rhs ;
   return result ;
}

"" :

Matrix & operator += (Matrix & result, const Matrix & rhs) ;
{
   // add rhs to result, and return result
   return result ;
}

Matrix operator + (Matrix lhs, const Matrix & rhs)
{
   return lhs += rhs ;
}

++, 27. , p48-49:

, @[@ +, -, ] . , , , .

+2

, , . , , .

-

, , operator+. , , . , . --, .

99% , . , - 2D 4D , - , , , - struct/class/.

, , , - DirectX OpenGL - .

+1

( ?), , , operator + , , . + = / - add(Matrix& result, const Matrix& in1, const Matrix& in2) .

, + .

+1

.

1) :

Matrix& operator+ (Matrix& other) const {

2) . , Matrix,

0

return:

Matrix Matrix::operator + (const Matrix& M)
{
    return Matrix(
        // 16 parameters defining the 4x4 matrix here
        // e.g. m00 + M.m00, m01 + M.m01, ...
    );
}

, .

0
source
class Matrix { 

  Matrix & operator+=(const Matrix & other) {
      // fill result with *this.data plus other.data 
      // elements += other elements 
      return *this;
  }
  Matrix operator+ (const Matrix & other) {
      Matrix result = *this; 
      return result += other; 
  } 
} 
0
source

All Articles