我可以使用该类中的函数删除动态分配的类吗?
我正在为游戏编写一个状态管理器。我已经了解了我想要如何做到这一点的大部分逻辑。 我希望状态(将是类)在 StateManager 类的堆栈中进行处理。每个状态都会有暂停函数,并且堆栈将是STL堆栈。
当一个状态完成了它需要做的事情(例如:在暂停屏幕上,用户单击“返回游戏”)时,需要将其从堆栈中删除并删除。我当前的逻辑(不幸的是,我无法测试)是这样的:
状态完成了它的工作。 在它的更新函数中,当它发现它完成时,它会调用一个函数来清理状态。 该函数将处理任何需要绑定的直接未解决的问题(如果有的话),从状态管理器堆栈中调用 pop 函数,并删除自身。
我要问的是:我可以从类内部删除类吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
请参阅 C++-FAQ-lite: 成员函数是否合法(和道德)说
删除这个?
See C++-FAQ-lite: Is it legal (and moral) for a member function to say
delete this?
你可以,甚至可以打电话:
但它有点毛茸茸的,丑陋的,可能很危险......
相关:
You can, it's even possible to call:
But it's kind of hairy and ugly and possibly dangerous...
Related:
当然:
当然,有很多事情您需要确定(其中最重要的是,如果您尝试对在堆栈上创建的实例执行此操作,则会遇到麻烦。
Sure:
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.