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;
What would you suggest or prefer? Thank.
++ , ( " ", 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), , , .
b+a
a+b
. R-Value http://www.artima.com/cppsource/rvalue.html
, , . , .
, - -, () .
, , , :
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:
, @[@ +, -, ] . , , , .
, , . , , .
-
, , operator+. , , . , . --, .
99% , . , - 2D 4D , - , , , - struct/class/.
, , , - DirectX OpenGL - .
( ?), , , operator + , , . + = / - add(Matrix& result, const Matrix& in1, const Matrix& in2) .
add(Matrix& result, const Matrix& in1, const Matrix& in2)
, + .
.
1) :
Matrix& operator+ (Matrix& other) const {
2) . , Matrix,
return:
Matrix Matrix::operator + (const Matrix& M) { return Matrix( // 16 parameters defining the 4x4 matrix here // e.g. m00 + M.m00, m01 + M.m01, ... ); }
, .
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; } }