c++ - Possible bug with GCC, foreach loops operate on shadows, rather than the actual objects -


i believe i've stumbled upon bug in gcc 4.82

consider following mcve:

class foreachtestobject {     std::string somevalue;  public:     foreachtestobject(int i)     {         somevalue = "default value "+to_string(i);     }      void resetsomevalue(string newvalue)     {         somevalue = newvalue;     }      string getvalue()     {         return somevalue;     } };  int main() {     vector<foreachtestobject> vec;     vec.push_back(foreachtestobject(1));     vec.push_back(foreachtestobject(2));      //reading via foreach unproblematic     for(auto obj : vec )     {         cout<<"object is: "<<obj.getvalue()<<endl;     }      //changing values inside foreach     (auto obj : vec)     {         obj.resetsomevalue("new name");     }      //printing second time     for(auto obj : vec )     {         cout<<"object is: "<<obj.getvalue()<<endl;     }//notice nothing has changed.      //now changing via conventional loop     (int = 0; i<vec.size();i++)     {         vec[i].resetsomevalue("this worked");     }      //printing third time     for(auto obj : vec )     {         cout<<"object is: "<<obj.getvalue()<<endl;     }//notice how values have been changed correctly. } 

running code through qts debugger, appears foreach loops create temporary copies of objects, memory addresses not match either of 2 actual objects. when resetsomevalue called, function on shadow objects called instead.

i might add not entirely sure qt compiles gcc 4.8.2. happen know updated gcc time ago, don't know if qt automatically takes use updated version. command gcc --version reports 4.8.2.

this strikes me down right odd, not mention inefficient, if each object iterated on copied, represent considerable overhead. according sources find, foreach loops should work in same manner conventional loops, yet here not.

when that's said, bug? if not, why?

for(auto obj : vec ) 

does , should create copies of elements of range, that's in language rules. if want reference, so:

for(auto &obj : vec ) 

Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -