|
course.wilkes.edu/CS125Labs |
||||
Experiment 6: Constant Reference Parameters
Actually, this one is more of a discussion than an experiment. The Question: Suppose I am writing a function, and one of its parameters is a class object that is received, but not passed back (i.e., whose movement is IN). If I declare the parameter as a value parameter, then when the function is called, a copy will be made of the corresponding (class object) argument. Since a class object is typically much larger than a character or number, copying a class object can take a lot of time, which means that passing a class object to a function via a value parameter can be very time-consuming. Is there any way to avoid wasting this time? The Answer. The key to solving this problem is to combine two seemingly unrelated pieces of information:
Piglatin() function this way:
string Piglatin(string englishWord)
{
// ...
}
If englishWord contains any word of more than 4 characters
(i.e., jeans), then the value parameter mechanism must
make a copy of this word. Copying more than 4 types requires more time
than storing a 32-bit address (4 bytes).
If we were to instead write our
string Piglatin(string & englishWord)
{
// ...
}
Then englishWord will store the 32-bit address of its corresponding
argument, and since 32 bits == 4 bytes, this will require less time
for any string of more than four characters.
However, this approach opens up a dangerous possibility of our function
mistakenly changing the value of
The solution is to declare
string Piglatin(const string & englishWord)
{
// ...
}
By preceding a reference parameter with the keyword const,
we tell the compiler to
|
Home Membership
|
|||
|
Last update: Wednesday, August 23, 2000 at 3:22:33 PM. |
||||