STL vector problem

Started by
11 comments, last by sanguineraven 20 years, 5 months ago
quote:Original post by Lektrix
In what way does "using STL" require a lot of copying?

What I mean by that is when you store something in a STL container you are truely storing a copy of the object. For any non-trivial class it costs more to copy an instance than copy a pointer.
What is Barrel Drop?
Who are HTS Games?
Advertisement
quote:Original post by Sabbac
quote:Original post by sanguineraven
Yeah I''m using pointers at the moment. It''s a vector of pointers to CEnemy. But for some reason when I use the draw method, its data is incorrect


Ah-Ha!

I bet it looks like this:
void fn(){  CEnemy temp;  temp.init(...);  m_enemies.push_back(&temp);}void otherFn(){  m_enemies[0]->draw(...);}If so the problem is that when temp goes out of scope the pointer to temp becomes invalid.Try this instead:   void fn(){  CEnemy* temp = new CEnemy;  temp->init(...);  m_enemies.push_back(temp);}void otherFn(){  m_enemies[0]->draw(...);}


hope that helps

[edit: speeling]

[edited by - sabbac on November 14, 2003 11:55:28 AM]


Yep!! That works, thankyou. I''ve been stuck on that for ages

Remember that you will need to free the dynamically allocated memory that the std::vector''s pointer elements address. Alternatively, you could use a smart pointer.

[ Google || Start Here || ACCU || STL || Boost || MSDN || GotW || CUJ || MSVC++ Library Fixes || BarrysWorld || E-Mail Me ]
[ Google || Start Here || ACCU || STL || Boost || MSDN || GotW || CUJ || MSVC++ Library Fixes || BarrysWorld || [email=lektrix@barrysworld.com]E-Mail Me[/email] ]

This topic is closed to new replies.

Advertisement