|
|
Blocks have two operators that make this possible. The first of these is an operator that converts from Block<T> to T*, where T is the Block element type. It is an inline function that simply returns a pointer to the first cell of the Block.
inline Block<T>::operator T*(const Block<T>& b){ return first_cell_ptr; }
When we call the first version of intcmp() with integer Blocks,
Block<int> a(100); Block<int> b(100);intcmp(a,b);
the compiler applies the conversion operator automatically to each operand. The generated code looks something like this (this is pseudocode):
intcmp( a.first_cell_ptr, b.first_cell_ptr );
so the cost of passing Blocks is the same as the cost of passing arrays.
The operator that makes the second version of intcmp() possible is the square brackets operator. Recall that, within the body of intcmp(), the square brackets operator was used several times, for example, in the expression
return s[i] - t[i];
The square brackets operator is also implemented as an inline:
inline T& Block<T>::operator [] (int i){ return *(first_cell_ptr + i); }
Since this is the same code that would be generated by an array index reference, there is no runtime overhead associated with this operation either.