Also how does the reference operator & effect index? is it copied? |
http://en.cppreference.com/w/cpp/language/copy_elision
When one returns a value from a function, there are a bunch of things the compiler tries to do implicitly:
* Copy Elision NRVO Named Return Value Optimisation
* Copy Elision RVO Return Value Optimisation
* Move Semantics - uses std::move implicitly if copy elision isn't feasible
* Copy - if everything else isn't feasible
So, one might not need to return by reference - it is already efficient because of the copy elision or move semantics.
As
cire points out, you may not need to return anything if using references for the function parameters - you have already changed the values of the variables.
Also be wary of returning a reference to something which goes out of scope at the end of the function.
Passing by reference is a term that includes both pointers and C++ references. In C, there are no references: passing by pointer is still called pass by reference, as opposed to pass by value.
So in summary, pass by reference if:
There is a need to change the value in the outer scope;
The object is an STL container or a class, struct - anything that might potentially have some large size.
Make the parameters const wherever it is valid to do so.
If not changing a value in the outer scope, don't bother to pass by reference for basic built-in types (int or double say) - it's not worth it.