Problem with push_back(Object)

Started by
5 comments, last by __fold 20 years, 5 months ago
I have this

//in class.h

private:
std::vector<Mathlib::Vector3<float> > points;

//in class.cpp


void class::myFunc()
{
  for(int i = 0; i <10; i++)
	points.push_back(Mathlib::Vector3<float>(i,2,3));
}

Now according to my book, this should be fine. But after each iteration in the for-loop. The destructor of the newly created Vector3 is called (since it''s goes out of scope). This also effects the vector of points. But shouldn''t the call to push_back make a copy of the vector?
Advertisement
push_back will call the copy constructor to initialize the points members. Assuming the vector class has a deep copy operation... or 3 separate date members for the components it will work fine.

EDIT: I just realised what you wanted to know. The value that is pushed back is a temporary, and this will be used to copy construct the points members. It will as you thought, go out of scope and be DESTROYED, HAHhaahaHHHHAHAHAAHAHH!!! This may or may not be a problem, as I described above.

[edited by - dmounty on October 23, 2003 6:21:37 AM]
Thanks.

I did sucha stupid mistake. The error was that I called .resize() instead of .reserve().
If you need speed, this might be better:
void class::myFunc(){    Mathlib::Vector3<float> v(0,2,3);    for(int i = 0; i < 10; i++) {        v.x = i; // or v[0] = i, v.set_x(i), or whatever	points.push_back(v);    }}
CWizard: I think the compiler will realize what''s going on and optimize it in this case. But if it was more advanced. Your solution might be be better both for optimization and for understanding the code.
never overestimate a compiler!
NEVER EVER BELIVE THAT THE COMPILER WILL DO THE WORK FOR YOU! (because thats just waiting to get pinched on your nose)
quote:Original post by Anonymous Poster
never overestimate a compiler!
NEVER EVER BELIVE THAT THE COMPILER WILL DO THE WORK FOR YOU! (because thats just waiting to get pinched on your nose)


BS!
The compiler will do stuff you just can''t imagine it would. Just read about how Visual Studio handles functions or how global optimization works. Another thing is that modern CPUs has predicition. So if it''s in a for-loop. You''re CPU might even optimize it and it won''t leave level 1 cache either I guess.

Another thing is that the guys who write compilers probably want the compilers to work best with proper no hack code. So making hacks is a great way to stop the compiler from doing proper optimizations.


Thanks for all the replies btw.

This topic is closed to new replies.

Advertisement