The question: Is there benefit to passing an integral type by const reference as opposed to simply by value.
ie.
void foo(const int& n); // case #1
<
well the cost of a reference is the same typically of that of an integral type, but with the reference you have an indirection that has to take place, because the reference to some memory has to be resolved into a value.
Just copy by value, stick to an immutable convention for built-in types.
It depends on the compiler, but I'd expect that any reasonable optimizer would give you the same results either way.
I tested with gcc, and the results were indeed the same. here's the code I tested:
inline int foo(const int& n) {
return n * 2;
}
int bar(int x) {
int y = foo(x);
return y;
}
(with and without const & on foo's n parameter)
I then compiled with gcc 4.0.1 with the following command line:
g++ -O3 -S -o foo.s foo.cc
The outputs of the two compiles were identical.
Please read Want Speed? Pass by Value by Dave Abrahams.
You can use boost::call_traits<your type>::param_type
for optimal parameter passing. Which defaults to simple parameter passing of primitive types and passing by const reference of structs and classes.
It's usually not worth it. Even for inline function, the compiler won't be stupid. The only time I would say it's appropriate is if you had a template; it might not be worth the extra effort to specialize for builtins just to take a copy instead of a reference.
When writing or using templates, you may end up with (const int &) because the template writer can't know what the type actually is. If the object is heavyweight, passing a reference is the right thing to do; if it's an int or something, the compiler may be able to optimize it away.
In the absence of some kind of external requirement, there is generally no reason to do something like this for a one-off function -- it's just extra typing, plus throwing around references actually tends to inhibit optimization. Copying small data in registers is much cheaper than reloading it from memory in case it's changed!