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

1

2 Answers 2

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.

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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.