Passing by reference in this case is certainly not more efficient by itself. Note that qualifying that reference with a const
does not mean that the referenced object cannot change. Moreover, it does not mean that the function itself cannot change it (if the referee is not constant, then the function it can legally use const_cast
to get rid of that const
). Taking that into account, it is clear that passing by reference forces the compiler to take into account possible aliasing issues, which in general case will lead to generation of [significantly] less efficient code in pass-by-reference case.
In order to take possible aliasing out of the picture, one'd have to begin the latter version with
void function( const double& x ) {
double non_aliased_x = x;
// ... and use `non_aliased_x` from now on
...
}
but that would defeat the proposed reasoning for passing by reference in the first place.
Another way to deal with aliasing would be to use some sort of C99-style restrict
qualifier
void function( const double& restrict x ) {
but again, even in this case the cons of passing by reference will probably outweigh the pros, as explained in other answers.