-1

I have a vector of cars

std::vector<Car> cars;

My question is why do the following iteration yeilds different results

for ( Car c : cars){
    std::cout << c.getID() << "--" << &c << std::endl;
}

This resulted in fixed address as follow:
1--0x61fef0
2--0x61fef0
3--0x61fef0
4--0x61fef0

while the following iteratioin resulted in unique address per item:

for(int i = 0; i < 4; i++){
    std::cout << cars[i].getID() << "--" << &cars[i] << std::endl;
 }

result:
1--0x8d18e8
2--0x8d18ec
3--0x8d18f0
4--0x8d18f4

my question is WHY?

stackunderflow
  • 3,811
  • 5
  • 31
  • 43
  • 7
    Because in the first version you are taking an address of **a copy** of the objects in vector. Change it to `for ( Car c& : cars)` and you'll get the same results as with the second version. – Yksisarvinen Nov 30 '19 at 23:20

1 Answers1

2

Your loop variable declaration Car c : cars requires copying cars from the vector. To avoid this and just reference the cars in-place in the vector, use const Car& c : cars or Car& c : cars instead.

jtbandes
  • 115,675
  • 35
  • 233
  • 266