c++ - Add addresses of Objects to a vector in loop -
i need create several objects , put them in list (for using std::vector). also, need list items point addresses of objects changes make objects reflected in list too. thing is, every item in list pointing last object created in 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 attributes of grass objects in list should be..
[0,0] [0,1] [0,2] . . . . [49,49]
but it's coming out be..
[49,49] [49,49] [49,49] [49,49] . . . [49,49]
you're pushing pointers local variables vector. local variables destroyed @ end of scope (the second-to-last }
in case). therefore, dereferencing of pointers after }
undefined behavior. output you're seeing valid result of undefined behavior.
using pointers here doesn't make sense. use them (including new
) when absolutely necessary. more info, see why should use pointer rather object itself?
this right way:
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); } }
Comments
Post a Comment