To avoid the inefficiency of copy-by-value when calling a function (say, "fillRect"), I want to pass the parameters by reference.
If I supply the parameters as declared local variables, it works fine. But if I supply any as "literal" integers, I get a compile error (no matching function).
void fillRect( int &x, int &y, int &width, int &height )
{
// do something
}
int x=10, y=20, w=100, h=80;
fillRect(x, y, w, h); // this compiles and works!
fillRect(x, y, 100, 80); // but this doesn't compile ... why?
What gives?
(Forgive my naivety: I’m pretty new to C++.)
As many people have pointed out, pass-by-reference isn’t generally appropriate as an optimisation for primitive types. This is excellent to know, so thank you all! Even so, my question was really more about why literal values can’t seem be passed by reference, which has been addressed by the accepted answer.
You cannot bind a literal to an lvalue reference to non-const (because modifying the value of a literal is not an operation that makes sense). You can however bind a literal to a reference to const.
So this will compile if you declare
fillRectas:In this case you are passing
ints.ints are so cheap to copy that passing by them by reference will probably make the performance of your program worse.The function
fillRectis probably so expensive that the cost of passing its arguments is totally irrelevant in any case. Or maybe it will be inlined, and there will be no cost whatsoever to passing the arguments. These sorts of micro-optimisations are usually not optimisations at all, and should always be guided by the results of profiling (if they are done at all).