困扰很久的bug,终于彻底顿悟了,废话不多说,先上代码
class Pos{
int x;
int y;
}
void main(){
std::vector<Pos> all_pos;
for(int i = 0 ;i < 10 ;i ++){
Pos newpos;
all_pos.push_back(newpos);
Pos &pos = all_pos[i];
pos.x = i;
pos.y = i;
}
}
for循环中会向all_pos中添加10个pos,然后再通过pos引用来修改all_pos中某个元素的值,但是pos在for循环中只会一直引用,导致最终所有的x、y都为9。