2

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);
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
klaus
  • 754
  • 8
  • 28

1 Answers1

2

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.

user513951
  • 12,445
  • 7
  • 65
  • 82
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • Then If I do not want the pointer to be copied, first case is better right ? Do you know a better solution to iterate on such a vector ? (if I want to prevent copy and if I do not want to modify object) – klaus Jan 11 '18 at 10:20
  • @klaus Yes. But for build-in types including pointers avoiding copy doesn't make much sense. And, what do you want the type of `item` to be? – songyuanyao Jan 11 '18 at 10:26
  • I want to be a pointer to Component. I think `for (auto& item : components)` is enough and if one day my vector becomes a vector of Components (and not Components*), it will still works... right ? – klaus Jan 11 '18 at 10:34
  • @klaus Well, then just `auto item : ...` seems fine. `auto&` makes `item` a reference to the element, if you change it point to another thing, the element is changed too. If that's what you want you should use reference. – songyuanyao Jan 11 '18 at 10:38