c++c++11autoranged-loops

Iterate through a const vector of pointers with auto


Let's say I have the following const vector of pointer :

const std::vector<Component*> components;

and I want to iterate through it and only calling a method on one element of this vector. Is it correct to do :

for (const auto& item : components) {
  method(item);
}

What is the difference with using :

for (auto item : components) {
  method(item);
}

with :

void method(Components* component);

Solution

  • Is it correct to do

    It depends on you.

    For the 1st case, the type of item will be Component* const&, which is a reference bound to the element of the vector.

    For the 2nd case, the type of item will be Component*, which (i.e. the pointer itself) is copied from the the element of the vector.

    The parameter type of method is Component*, means passing the pointer by value/copy, then there's no actual difference between the 2 cases. And for pointer (as built-in type), just auto item : components is fine here.