Mentioning const early and often tells the code reader more about what happens if the reader does not need to look further in the code.
Now, given your code, I would write it as:
void print_book(const std::vector<Entry>& book) { for (auto&& x : book) std::cout << x << '\n'; }
or even:
void print_book(std::experimental::array_view<const Entity> book) { for (auto&& x : book) std::cout << x << '\n'; }
but just because the code is so short, I would omit the redundant const .
(the array_view version eliminates the useless dependency on the argument being vector - vector<?> const& , usually with your interface, since vector<?> const& does not provide anything useful that array_view<?> does not, but can force copy from initialization lists or from source arrays of C, etc.)
There is no reason to use const auto& over auto& or auto&& with respect to the compiler, since all 3 (in this context) are inferred with the same type. The only reason to use one or the other is to talk with other programmers.
In my case, I use auto&& by default (it says that I am iterating and I don't care what I repeat).
auto& If I know what I need to change, and auto const& if I want to emphasize that I do not change.
Yakk Jun 03 '16 at 14:10 2016-06-03 14:10
source share