After destructor is called,

Started by
10 comments, last by rip-off 12 years, 8 months ago
Everytime i 'kill' a monster i delete it. After its destructor is called i get this..

Unhandled exception at 0x68129397 in MyGame.exe: 0xC0000005:
Access violation reading location 0xfeeeff26.
Advertisement
Do you call delete twice on the same pointer or something? It's just a guess because it's hard to know by just looking at that error message.
hmm.. maybe? Is there a way to check that? like.. if( not deleted){ delete }

hmm.. maybe? Is there a way to check that? like.. if( not deleted){ delete }


From what i khnow there is no way to do it. You cannot check if you have alreasy called delete on a pointer.

Generally the idea is: if someone allocates memory, that someone has to free it.
No. There is no way to tell. That's the exciting challenge of C++. It's also why smart pointers were invented. Smart pointers mean you never have to explicitly call delete again.

Stephen M. Webb
Professional Free Software Developer


No. There is no way to tell. That's the exciting challenge of C++. It's also why smart pointers were invented. Smart pointers mean you never have to explicitly call delete again.


I agree. Get the hang of using shared_ptr and weak_ptr and you wont look back.
Don't thank me, thank the moon's gravitation pull! Post in My Journal and help me to not procrastinate!
I know from your previous posts that you store monster pointers in a vector. If you delete the monster from the vector you probably also want to remove the pointer from the vector. One way of doing that is to use std::vector::erase. It takes an iterator as argument but I'm not going to explain iterators now so I just give some code.
for(std::size_t i = 0; i < monsters.size(); i++ )
{
if(monsters->IsDead())
{
delete monsters;
monsters.erase(monsters.begin() + i); // this removes the pointer from the vector
}
}

Note that all monster after the deleted monster will move down one index in the vector and the size of the vector will be one smaller.
Thanks for that Wooh! But that doesnt change the fact that after the destructor is finished, i get that error.

EDIT: Oh... nvm your suggestion did fix it!
Just one last question for tonight:

When a monster dies i do this "player->points += 100". But since after the monster dies that will always be true, it keeps adding 100 each frame. How do i stop that?
You mean IsDead() is always true? When the monster has been deleted you never call IsDead() on it again so that shouldn't cause any problems I think. I can't see your code so I just speculating.

This topic is closed to new replies.

Advertisement