using reference and pointer for operator overloading on large objects
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 ca开发者_Python百科nnot 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.,
Matrix operator+(Matrix arg1, Matrix arg2)
then copies of arg1
and arg2
would have to be made to be passed into the function. A simple matrix addition, e.g.,
Matrix x, y;
x + y;
would require copies of both x
and y
to be made; effectively, you end up having to copy 32 double
s, 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 its std::istream
operand 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 + y
as shown above, you would need to use &x + &y
.
The "excessive copying" part is simple. If there were no &
in the parameter list, the matrices would be copied when being passed in.
References are similar to C++ pointers in some ways, and they are almost always implemented using pointers internally. One of the differences, which the book notes, is that you can use operator overloading on references to an instance of a classs.
However, you can't do the below (or any equivalent syntax):
Matrix operator+(const Matrix *arg1, const Matrix *arg2)
So you can't write:
Matrix *a, *b, *c;
c = a + b;
The reason for not allowing user defined operators for built-in types, like pointers or ints, is of course that they already have operators defined for them by the language.
精彩评论