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);
It depends on you.
For the 1st case, the type of
itemwill beComponent* const&, which is a reference bound to the element of thevector.For the 2nd case, the type of
itemwill beComponent*, which (i.e. the pointer itself) is copied from the the element of thevector.The parameter type of
methodisComponent*, means passing the pointer by value/copy, then there's no actual difference between the 2 cases. And for pointer (as built-in type), justauto item : componentsis fine here.