将对象的地址添加到循环中的向量 [英] Add addresses of Objects to a vector in loop
问题描述
我需要创建几个对象并将它们放在列表中(我正在使用std :: vector).另外,我需要列表项指向对象的地址,以便我对对象所做的更改也反映在列表中.但事实是,列表中的每个项目都指向循环中创建的最后一个对象.
I need to create several objects and put them in a list (for which I am using std::vector). Also, I need the list items to point to the addresses of the objects so that the changes I make to the objects are reflected in the list too. But the thing is, every item in the list is pointing to the last object created in the loop.
for(int i=0;i<50;i++){
for(int j=0;j<50;j++){
Grass g1;
g1.position.x = i;
g1.position.y = j;
grassList.push_back(&g1);
}
}
列表中的草对象的属性应该是..
The the attributes of grass objects in the list should be..
[0,0]
[0,1]
[0,2]
.
.
.
.
[49,49]
但是它即将出现..
[49,49]
[49,49]
[49,49]
[49,49]
.
.
.
[49,49]
推荐答案
您正在将指向局部变量的指针推入向量.局部变量在其作用域的末尾被销毁(本例中倒数第二个}
).因此,在}
之后取消引用这些指针中的任何一个都是未定义的行为.您看到的输出是未定义行为的完全有效结果.
You're pushing pointers to local variables to the vector. Local variables get destroyed at the end of their scope (the second-to-last }
in this case). Therefore, dereferencing any of those pointers after the }
is undefined behavior. The output you're seeing is a completely valid result of undefined behavior.
在这里使用指针是没有意义的.仅在绝对必要时使用它们(包括新的代码).有关更多信息,请参见为什么我应该使用指针而不是对象本身?
Using pointers here just doesn't make sense. Use them (including new
) only when absolutely necessary. For more info, see Why should I use a pointer rather than the object itself?
这是正确的方法:
std::vector<Grass> grassList;
// ^^^^^ not pointers!
for(int i=0; i<50; ++i) {
for(int j=0; j<50; ++j) {
Grass g1;
g1.position.x = i;
g1.position.y = j;
grassList.push_back(g1);
}
}
这篇关于将对象的地址添加到循环中的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!