Archived

This topic is now archived and is closed to further replies.

__fold

Problem with push_back(Object)

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites
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);
}
}

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Guest 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)

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites