May 28, 2013 at 9:10am May 28, 2013 at 9:10am UTC
I'm following this tutorial: http://devmaster.net/posts/3232/how-to-structure-a-game
After reading this I wrote a practice program and my problem came when I wanted to delete something from the list. Here is my program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
#include <iostream>
#include <list>
class Apple
{
private :
static std::list <Apple *> applePtrVector;
std::list <Apple *>::iterator iterator;
void Destroy();
public :
Apple();
~Apple();
static void DestoryAll();
};
void Apple::Destroy()
{
delete this ;
}
Apple::Apple()
{
applePtrVector.push_front(this );
this ->iterator = applePtrVector.begin();
}
Apple::~Apple()
{
applePtrVector.erase(this ->iterator);
}
void Apple::DestoryAll()
{
for (std::list <Apple *>::iterator i = applePtrVector.begin(); i != applePtrVector.end(); i++)
{
(*i)->Destroy();
}
}
std::list <Apple *> Apple::applePtrVector;
int main()
{
new Apple;
new Apple;
new Apple;
new Apple;
Apple::DestoryAll();
return 0;
}
On the first call of 'delete this' I get the error "list iterator not incrementable". I realise I could use applePtrVector.clear but what if I needed to call 'delete this' in an update function?
Thanks,
Rowan.
Last edited on May 28, 2013 at 9:11am May 28, 2013 at 9:11am UTC
May 28, 2013 at 9:23am May 28, 2013 at 9:23am UTC
Haha, works perfect thanks! But why?
May 28, 2013 at 10:36am May 28, 2013 at 10:36am UTC
@Rowan836
Haha, works perfect thanks! But why?
Because
before deleting a node you get the next
valid iterator by using the postincrement.
In your original code
after deleting a node the iterator becames invalid.
Last edited on May 28, 2013 at 10:36am May 28, 2013 at 10:36am UTC