1

I am learning C++ and I have problem to understand why this works. I understand that a reference is just synonym for a certain object. But I do not understand why this

std::vector<int> v{1,2,3};
for (auto &i : v)      //using reference
    i *= i;

outputs 1,4,9 and this

std::vector<int> v{1,2,3};
    for (auto i : v)   //without using reference
        i *= i;

outputs 1,2,3?

Thank you in advance

zenzu
  • 51
  • 5
  • this answers you https://stackoverflow.com/questions/15176104/c11-range-based-loop-get-item-by-value-or-reference-to-const – asmmo Apr 04 '20 at 20:02

2 Answers2

1

It's the same reason why:

int a=2;

int &b=a;

b=3;

why this ends up setting a to 3, but:

int a=2;

int b=a;

b=3;

a is still 2, and only b is 3.

The vector itself is irrelevant, this has to do with the basic concept of what a reference is. A reference creates an alias for the referenced object. A "non-reference" creates a new object. auto &i creates a reference. auto i creates a new object and initializes it by copying its value from another object, in this case each value in the vector.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
0

The reference is actually a reference to a certain object in memory.

So when you do auto &i you create a reference to an object (in that case it is an element from the vector). Any operations are performed on the referenced object - i.e. the element of the vector. i *= i changes the value of the element, because i is the reference to this element.

And when you do auto i you create a new variable (object) which is being stored on a stack. That object only lives in the scope of the for loop. So the changes made to it do not affect any other data.

Hope this helps.

Dmitrii Abramov
  • 106
  • 1
  • 5