Is this correct?:
std::vector<Enemy*> enemies;
enemies.push_back(new Enemy());
Enemy* enemy = enemies[0];
enemies.erase(enemies.begin() + 0);
delete enemy;
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It works, yes, but it’s not an ideal approach.
Firstly, adding 0 is just noise, you can remove that. But even better, just use
pop_front(). Also, no need for the intermediate step, you can delete before removing.But
std::vectorisn’t good as popping from the front, especially if it’s large (because the remaining elements need to be shifted to fill the void). If you don’t need contiguous memory, use astd::dequeinstead. Or, if order doesn’t matter, you can use something like this:It swaps the front element with the back element, then pops it off. Of course, order is not retained.
The other problem is with your approach to memory management. Anytime you have explicit clean up code, you’ve done something wrong. It should be done automatically.
Use either Boost’s
ptr_vector, or astd::vectorof smart pointers. (Note: do not usestd::auto_ptrin a container, it’s broken in this regard.) For a quick smart pointer suggestion, use eitherstd::unique_ptr(if your compiler supports C++0x), orstd::/boost::shared_ptr.