>
>
>
V834. Incorrect type of a loop variable…


V834. Incorrect type of a loop variable. This leads to the variable binding to a temporary object instead of a range element.

The analyzer detected implicit copying of container elements at each iteration of the loop. The developer assumed that the loop variable of the reference type would bind to the elements of the container without copying. This happens because loop variable types don't match container elements.

Look at the example:

void foo(const std::unordered_map<int, std::string>& map)
{
  for (const std::pair<int, std::string> &i : map)
  {
    std::cout << i.second;
  }
}

In this fragment, the developer wanted to go through all elements of the 'std::unordered_map' container in the loop and print the values to the output stream. However, the elements don't have the 'std::pair<int, std::string>', types as expected, but have the 'std::pair<const int, std::string>' types. If arguments of the 'std::pair' template don't match them, each element of the container will be implicitly converted to a temporary object of type 'std::pair<const int, std::string>'. Then the reference will be bound to it.

You can solve this problem in two ways:

The first way. Use the correct type of a loop variable. In general, you just need to see what value type the iterator of the used container returns when dereferencing (operator *).

void foo(const std::unordered_map<int, std::string> map)
{
  for (const std::pair<const int, std::string> &i : map)
  {
    std::cout << i.second;
  }
}

The second way. Use the 'auto' type to automatically output the type of container elements.

void foo(const std::unordered_map<int, std::string> map)
{
  for (const auto &i : map)
  {
    std::cout << i.second;
  }
}

Obviously, the second method is more convenient, since it reduces the amount of code and eliminates the possibility of writing the wrong type.