View Single Post
  #46  
Old August 17th, 2006, 11:53 PM
PvK's Avatar

PvK PvK is offline
National Security Advisor
 
Join Date: Dec 1999
Posts: 8,806
Thanks: 54
Thanked 33 Times in 31 Posts
PvK is on a distinguished road
Default Re: OT: Stupid c++

Destructors are simply functions that get called when an object is deleted. If you never use new or malloc, then you probably never use delete nor free either, and your objects will only be deleted automatically - i.e. if they are local to a function and that function exits, or when the program exits. In other words, it sounds like you probably don't need to worry about destructors at all.

What are you going to do about creating new things during play, though, like new monsters, items, levels, etc.? Are you using STL lists of objects (not of pointers to objects) and just adding them and removing them from those? If so, then imagining how your code probably looks, STL should be doing the cleanup for you, and you shouldn't need to define destructors...

... well, ok, as long as you don't start using pointers or references to items in those lists, and expecting them to always be there after other events have happened that might have removed them from the lists. That could lead to a nice invalid pointer or reference and crash.

Example:

Say you have a list of all monsters in the world called MonsterList. Then say you have a Quest object to slay a particular monster, which when it gets launched, adds a monster to MonsterList and then keeps a pointer or reference to that monster object, to refer to the monster to slay. Now, if something in the game can remove the monster from MonsterList, causing its object to be automatically deleted by STL, then referring to a reference or pointer to it will be an access violation and boom. So if you want to avoid that, you could give monsters also a unique ID, and when you refer to them, always go search the list.

Of course, that's a fairly slow operation, but you probably don't care too much until you have thousands of things going on at once in your gameworld. To be faster, you could have a destructor that announces when something gets deleted, and causes everything that might refer to it to drop their pointers and references to it. Sounds like you'd probably be better off keeping things simple and reliable for now, though.
Reply With Quote