tags:

views:

150

answers:

4

I'm writing a state manager for a game. I've got most of the logic down for how I want to do this. I want states, which will be classes, to be handled in a stack in the StateManager class. Each state will have pause functions, and the stack will be an STL stack.

When a state is done with what it needs to do (example: from the pause screen, the user clicks "return to game") it needs to be removed from the stack and deleted. My current logic (which I have been unable to test, unfortunately) would be this:

State finishes its job. In its update function, when it finds that its done, it will call a function to clean up the state. This function will take care of any immediate loose ends that need to be tied (if there are any), call the pop function from the state manager stack, and delete itself.

What I'm asking is: can I delete a class from within itself?

A: 

You can, it's even possible to call:

delete this;

But it's kind of hairy and ugly and possibly dangerous...

Related:

Jesper
Well, is there a better method? My second idea was having an "is_done" variable or something that the state manager would check every cycle and pop and delete states that are "done". I don't know how resource-intensive that would be.
sonicbhoc
You could have something like Qt's QObject::deleteLater() method... it adds the object to a list, and at some later point (e.g. at the start of the next iteration through your event loop) goes through the list and deletes everything in it. It may be a good idea to also set a in_delete_laterlist flag in the object, and have deleteLater() check that flag, so that if deleteLater() gets called on the object more than once, it won't get added to the list twice and deleted twice.
Jeremy Friesner
A: 

Sure:

void cleanup(){
 delete this;
}

Of course there are a lot of things you need to be sure of (not the least of which is that you will have badness if you try to do that with an instance that was created on the stack.

Dolphin
A: 

Yes - delete this; is valid. Just be sure that this is the last thing related to the class that is done in the function that does the delete.

Stephen Doyle
+6  A: 

See C++-FAQ-lite: Is it legal (and moral) for a member function to say delete this?

As long as you're careful, it's OK for an object to commit suicide (delete this).

Igor Oks