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); 
0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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 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?
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 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.