Don’t forget that in C/C++ the compiler needs to be able to compile a call to a function based only on the function declaration.
Given that callers might be using only that information, there’s no way for a compiler to compile the function to take advantage of the optimization you’re talking about. The caller can’t know the function won’t modify anything and so it can’t pass by ref. Since some callers might pass by value due to lack of detailed information, the function has to be compiled assuming pass-by-value and everybody needs to pass by value.
Note that even if you marked the parameter as ‘const
‘, the compiler still can’t perform the optimization, because the function could be lying and cast away the constness (this is permitted and well-defined as long as the object being passed in is actually not const).
I think that for static functions (or those in an anonymous namespace), the compiler could possibly make the optimization you’re talking about, since the function does not have external linkage. As long as the address of the function isn’t passed to some other routine or stored in a pointer, it should not be callable from other code. In this case the compiler could have full knowledge of all callers, so I suppose it could make the optimization.
I’m not sure if any do (actually, I’d be surprised if any do, since it probably couldn’t be applied very often).
Of course, as the programmer (when using C++) you can force the compiler to perform this optimization by using const&
parameters whenever possible. I know you’re asking why the compiler can’t do it automatically, but I suppose this is the next best thing.