More call-by-reference |
Call-by-reference can be used in place of call-by-value if you don't want to copy an entire parameter over (call-by-value always makes a copy of the parameter). To indicate that it should not be changed (i.e., you are really only doing this for efficiency), you need to mark the parameter as const. For example, we can write
boolean find(string target, const vector<string> & set);
You shouldn't need to do this much unless you are passing around arrays or other large structures. However, you are likely to see it in code. When a parameter is marked as const, only const methods (accessors) are allowed to be sent to it and you may not assign to it.
By the way, there are also reference variables, which are used to alias another variable, and which are implicitly dereferenced when used. E.g.,
int orig = 7; int & alias = orig; alias++; cout << orig << endl;
ends up printing out 8.
Can also define a function to return a value by reference, but you must ensure that the address returned still exists after the return! Using return by reference does not create a new copy of an object. Thus if m() uses return by reference then
string & m() {...} ... string & shareString = m(); // no copying string copyString = m(); // copy is made by assignment
We will see this used with the assignment operator. The only reason for doing this is for efficiency reasons!
More call-by-reference |