0

Suppose a class Object exists.

I now have vector<Object> vec

If I now do in some part of my code:

for(auto p : vec){
   //something with p
}

Does this make a new object p for every object that actually in the iterator? Or does it actually just go through the actual objects in the list? I'm asking because I've also seen auto& p

Brijendar Bakchodia
  • 1,567
  • 1
  • 9
  • 15

2 Answers2

3

Yes, it will make a copy of each item, to have a reference you should do:

for (auto& p : vec) {}

Also, if you want to protect items from any change, you can have const to reference:

for (const auto& p : vec) {}
masoud
  • 55,379
  • 16
  • 141
  • 208
1

The range based for loop you have

for(auto p : vec) /* ... */

copies every element in vec into the loop variable p. Hence, any changes you apply to p does not affect the elements in vec. And yes, if you change the loop to

for (auto& p : vec) /* ... */

then p is a reference to the vec elements, and changes applied to p are changes you apply to the corresponding vec element.

lubgr
  • 37,368
  • 3
  • 66
  • 117