I wrote this code to try and understand a bigger problem in some other larger code, but in the second iteration over the list in main prints garbage and I don't quite get what is going on here. Admittedly I tend to break pointers, but here it looks straight forward to me, anyone have any insight?
std::list<int *> myobjects;
const std::list<int *>& getMYObjects( void );
const std::list<int *>&
getMYObjects( void )
{
return( myobjects );
}
void fillMYObjects()
{
int myints[]={15,36,7,17,20,39,4,1};
for(int i=0;i<8;i++)
{
int *temp = &myints[i];
myobjects.push_back(temp);
std::cout << "list: " << *temp << std::endl;
std::cout << "list: " << temp << std::endl;
}
std::cout << "listBack: " << *myobjects.back() << std::endl;
for(std::list<int*>::iterator it=myobjects.begin(); it!=myobjects.end();++it)
{
std::cout << ' ' << **it << std::endl;
}
}
int main()
{
fillMYObjects();
std::list<int*> myobjects2 = getMYObjects();
for(std::list<int*>::iterator it=myobjects2.begin(); it!=myobjects2.end();++it)
{
std::cout << ' ' << **it << std::endl;
}
}
The variable myints
is a local variable, and will go out of scope once the function returns. What happens to the pointers in the list then? The will point to memory now occupied and overwritten objects.