Re: When to use "call by reference"?
The rules of thumb are very simple, actually:
- If a parameter is changed within a function and you're interested in the
result, then pass by reference. Example:
[snip]
- If a parameter is big enough (i.e., its copy is expensive) and you don't
want it to be changed within a function, then pass by const reference.
Example:
[snip]
- If a parameter is small and trivial enough (i.e., its copy is cheap) and
you don't care about its changes within a function, then pass by value.
Example:
[snip]
There's just one complication whereby pass by const reference acts
differently from pass by value, which is when another, non-const, means of
accessing the target exists inside the called function, in which case pass
by value will refer to the original value of the target at the time of the
call, while the const reference will track the changed value.
Const reference doesn't mean "reference to a variable that doesn't change",
it means "a reference that can only be used to read a variable".
Example:
#include <iostream>
using namespace std;
int x;
void f1(const int& y)
{
x = 2;
cout << y << endl; // prints 2
}
void f2(int y)
{
x = 10;
cout << y << endl; // prints 0
}
int main(int argc, char** argv)
{
x = 0;
f1(x);
x = 0;
f2(x);
return x; // returns 10
}