The copies are due to the fact that you are iterating a map but binding the wrong reference type. The value_type
for that map is std::pair<const int, X>
(note the const
). Because they are not the same type, the compiler is creating a temporary and binding the reference.
You can (probably should) iterator using auto&
or const auto&
in most cases, which will avoid this kind of issues. If you want spell out the type, you can use the nested value_type
or the exact type:
for (const std::map<int,X>::value_type& r : numbers) {
// or
for (const std::pair<const int,X>& r : numbers) {
The preference should be: const auto& r
then const std::map<...>::value_type&
and then const std::pair<const int, X>&
. Note that the further to the right in the list, the more knowledge you are providing and the less you allow the compiler to help you.