recently I've encountered very very peculiar question when using auto in C++, just ... just look at the following code snippet :
my main function:
#include <list> #include <iostream> #include <stdio.h> int main(){ int a = 10, b = 20, c = 30; list<int> what; what.push_back(a); what.push_back(b); what.push_back(c); read(what); return 0; } And here's function read:
void read(const list<int>& con){ for (auto it : con){ printf("%p\n", &it); cout << it << endl; } return ; } And here's is the output :
0x7fffefff66a4 10 0x7fffefff66a4 20 0x7fffefff66a4 30 What the heck is that? Same address with different content !?
And more strange this is, if I modify the for-loop by adding an '&'
that is:
for (auto& it : con){ All the output makes sense immediately, the addresses would change by iteration
So my question is,
Why does the '&' sign make a change under this circumstance?
&in its different forms.auto, it's about iterators. Replaceautowithint, same results.