Note that your first naive implementation is very native, as nothing is passed by reference. I'll assume this was a really naive example and that there is no need to remind readers of the benefits of passing by-reference instead of by-value.
Note, too, that I have used the non-member-function operators, instead of the member-functions, but in the end, the results are (almost) the same.
If you want to be sure no necessary copy will be created, you should try a non-operator version:
void add(Matrix & result, const Matrix & lhs, const Matrix & rhs) ;
If you want to do it the operator way (which is my prefered solution), then you should assume operator + will create a temporary. You should then define both operator + and operator += :
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 ;
}
Now, you could try to "leverage" compiler optimisations and write it as:
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 ;
}
As proposed by Herb Sutter in C++ Coding Standards, 27. Prefer the canonical forms of arithmetic and assignment operators, p48-49:
A variation is to have operator @ [@ being +, -, whatever] accept its first parameter by value. This way, you arrange for the compiler itself to perform the copy for you implicitely, and this can give the compiler more leeway in applying optimizations.