#include <iostream>
#include<list>
using namespace std;
int main()
{
list<int *>l;
for(int i=0;i<3;i++)
{
int a = i;
l.push_back(&a);
}
cout<<endl;
for(auto i=l.begin();i!=l.end();i++)
{
cout<<**i<<" ";
}
return 0;
}
The output I get is 2 2 2
. Is it because, the compiler is creating the new variable at the same address everytime??
Edit1: The code is not doing anything. I just wrote this code as an experiment. Also if the code is written like this:
#include <iostream>
#include<list>
using namespace std;
int main()
{
list<int *>l;
for(int i=0;i<3;i++)
{
int *a = new int;
*a = i;
l.push_back(a);
}
cout<<endl;
for(auto i=l.begin();i!=l.end();i++)
{
cout<<**i<<" ";
}
return 0;
}
Now i get the output 0 1 2
. What is the difference between the two? Isn't also the pointer destroyed after the loop runs once??