Is it possible to remove a dynamically allocated class using a function inside that class?

I am writing a state manager for the game. I have most of the logic for how I want to do this. I want the states to be classes handled on the stack in the StateManager class. Each state will have pause functions and the stack will be an STL stack.

When a state is executed with what it needs to do (for example: from the pause screen, the user presses back to play), it needs to be removed from the stack and removed. My current logic (which I was unfortunately unable to verify, unfortunately):

The state is completing its work. In its update function, when it detects that it is done, it will call a function to clear the state. This function will take care of any loose ends that need to be anchored (if any), call pop from the state manager stack and pop yourself.

I ask: can I remove a class from myself?

+2


source to share


4 answers


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



As long as you are careful, it is okay for the subject to commit suicide (delete that).

+6


source


You can, you can even call:

delete this;

      

But this is somehow hairy and ugly and possibly dangerous ...



on this topic:

0


source


Sure:

void cleanup(){
 delete this;
}

      

Of course, there are a lot of things you need to be sure about (not least because you will get in trouble if you try to do this with an instance created on the stack.

0


source


Yes - delete this;

. Just make sure it's the last thing that has to do with the class that is being executed in the function that does the deletion.

0


source







All Articles