Search code examples
c++self-destruction

Can I delete a dynamically allocated class using a function within that class?


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?


Solution

  • 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).