I’m not sure if the snippet of C++ code below is legitimate or not:
std::vector<int*> myints;
for (int i = 0; i<N; i++) {
int j = i;
myints.push_back(&j);
}
for (int i=0; i<myints.size(); i++) cout<<*(myints[i])<<endl;
How does the compiler handle this ? I understand the variable j itself goes out of scope when exiting the for loop but will an integer be locally allocated N times on the stack so that the int objects pointed to by the elements in the vector remain valid outside the loop ?
Many Thanks !
-bert
Once the block ends, the compiler stops caring about the memory that was previously reserved for them. But even if nothing else disrupts that, you have another problem: all the
int*s in thevector<int*>point to the same memory location, so they all have the final value ofi.