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:
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 PigLatin() function as follows:
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 englishWord which, since the movement of englishWord is IN, would be a logic error. If it were to make this error, the compiler would be unable to point out our mistake, since we have declared englishWord as a reference parameter.
The solution is to declare englishWord as a const reference parameter:
string Piglatin(const string & englishWord)
{
// ...
}
By preceding a reference parameter with the keyword const,
we tell the compiler to
Forward to the Next Experiment