I expect the program prints the numbers 0 to 99, but when I run the code I
see 100 lines of 99
I have a class foo:
class foo{
public:
int i;
};
And a class bar:
class bar{
public:
foo* foo_;
};
And a code similar to:
int i=0;
vector<bar*> fs;
while(i<100){
foo f;
f.i = i;
bar* b = new bar;
b->foo_ = &f;
fs.push_back(b);
i++;
}
I expect that each bar->foo_ refer to a different foo, so when i have:
for(i=0;i<fs.size();i++){
cout << (fs[i]->foo_->i) << "\n";
}
I expect the program prints the numbers 0 to 99, but when i run the code i
see 100 lines of 99!!
why all pointers refers to the last object?
No comments:
Post a Comment