In the book of “The C++ Programming Language”, the author gives the following example and several claims.
class Matrix {
double m[4][4];
public:
Matrix( );
friend Matrix operator+(const Matrix&, const Matrix&)
};
Matrix operator+(const Matrix& arg1, const Matrix& arg2)
{
Matrix sum;
for (int i=0; i<4; i++)
sum.m[i][j ]=arg1.m[i][j]+arg2.m[i][j];
return sum;
}
The book claims that
references allow the use of expressions involving the usual arithmetic operators for large objects without excessive copying. Pointers cannot be used because it is not possible to redefine the meaning of an operator applied to a pointer.
I do not understand what does “excessive copying” refer to in the above statement. And for the statement of “Pointers cannot be used because it is not possible to redefine the meaning of an operator applied to a pointer”, I am just totally lost. Thanks for the explanation.
If
operator+was instead declared as taking its operands by value, e.g.,then copies of
arg1andarg2would have to be made to be passed into the function. A simple matrix addition, e.g.,would require copies of both
xandyto be made; effectively, you end up having to copy 32doubles, which, while not extremely expensive in this case, is not particularly cheap either. When you take an argument by reference, no copy has to be made.Note that some operator overloads must take their argument by reference. As a common example, consider the
<<stream insertion operator: it must take itsstd::istreamoperand by reference because it is impossible to copy the stream.Pointers cannot be used because operators cannot be overloaded for pointers: at least one operand of each operator overload must be a class or enumeration type. Even if you could use pointers, the syntax would be very awkward; instead of using
x + yas shown above, you would need to use&x + &y.