oh, helios XD
Anyway....
- passing by value makes a copy.
- passing by reference involves an indirection.
Both have tradeoffs. Whether or not passing by value is "worth it" depends on a number of things. Including how expensive a copy is, how often the variable is used in the function, and how the compiler decides to compile the code.
Generally (and these are very general rules):
1) Large objects or classes should be passed by reference. The rationale is that larger objects will be more expensive to copy.
2) Classes that have no/few public data members (but have public member functions) should be passed by reference. The rationale is that member functions require an indirection ANYWAY (for the this pointer), and so there's no point in creating the copy since it doesn't spare you any indirection.
3) Small primitive types should be passed by value. The rationale is that making a copy of an int is as inexpensive as it gets. Passing an int by reference makes a copy of the pointer to the int (just as slow or slower than copying the int), AND you get indirection on top of that.
4) When passing by reference, pass by const reference to make it clear the object will not be changed. Only pass by nonconst reference if the function is expected to change the passed parameter. This is a clarity thing and it makes your code much easier to follow.
*) Note that if the function is inlined and/or very small, the compiler might be able to optimize out the copy/indirection anyway.
----------------------
Now that all of that is out of the way... as for the original example -- prefer the getScore that returns an int. The reasons for this:
It lets you compound the statement easier. IE: you can pass getScore as a parameter, or use it in a computation without having to use a temp variable:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
// if it returns, you can do things like this:
setHighScore( getScore() );
int nextmilestone = getScore() + 1000;
//------------------
// if it's passed by ref, you have to make temp vars:
int temp;
getScore(temp);
setHighScore(temp); // 3 lines vs 1, additional variable
int nextmilestone;
getScore(nextmilestone);
nextmilestone += 1000; // 3 lines instead of 1, not as clear
|