开发者

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.开发者_JAVA技巧

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


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


You can, it's even possible to call:

delete this;

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

Related:

  • Should objects delete themselves in C++?
  • Is it OK to use “delete this” to delete the current object?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜