Let us consider the following example (of course this should be replaced by std::accumulate
):
#include <vector>
auto sum(std::vector<int> const& numbers) -> int
{
auto sum = 0;
for(auto /*const, const&, &&, [nothing]*/ i : numbers) { sum += i; }
return sum;
}
As you see, there are many different ways to use the ranged-based for loop for small types.
Note that all of these variants compiled to the same assembly code in compiler explorer using gcc
.
I often see the recommendation to use auto i
in the first case and auto const& i
in the second case.
But we are talking to the compiler and not the human here. The interesting information is that the variable is only input. This is not expressed by auto i
.
So is there any performance-disadvantage of using auto const& i
instead of auto i
in any situation where you only need to read the input?