If all a function needs to do with a parameter is see its value, shouldn’t you always pass that parameter by constant reference?
A colleague of mine stated that it doesn’t matter for small types, but I disagree.
So is there any advantage to do this:
void function(char const& ch){ //<- const ref
if (ch == 'a'){
DoSomething(ch);
}
return;
}
over this:
void function(char ch){ //<- value
if (ch == 'a'){
DoSomething(ch);
}
return;
}
They appear to be the same size to me:
#include <iostream>
#include <cstdlib>
int main(){
char ch;
char& chref = ch;
std::cout << sizeof(ch) << std::endl; //1
std::cout << sizeof(chref) << std::endl; //1
return EXIT_SUCCESS;
}
But I do not know if this is always the case.
I believe I’m right, because it does not produce any additional overhead and it is self documenting.
However, I want to ask the community if my reasoning and assumptions are correct?
Even though the
sizeof(chref)is the same assizeof(ch), passing character by reference does take more bytes on most systems: although the standard does not say anything specific about the implementation of references, an address (i.e. a pointer) is regularly passed behind the scenes. With optimization on, it probably would not matter. When you code template functions, items of unknown type that will not be modified should always be passed by const reference.As far as small types go, you can pass them by value with a
constqualifier to emphasize the point that you aren’t going to touch the argument through the signature of your function: