我可以使用该类中的函数删除动态分配的类吗?

发布于 2024-08-07 15:05:44 字数 325 浏览 2 评论 0原文

我正在为游戏编写一个状态管理器。我已经了解了我想要如何做到这一点的大部分逻辑。 我希望状态(将是类)在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

时光沙漏 2024-08-14 15:05:44

请参阅 C++-FAQ-lite: 成员函数是否合法(和道德)说删除这个?

只要小心,对象自杀是可以的(删除这个)。

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

千仐 2024-08-14 15:05:44

你可以,甚至可以打电话:

delete this;

但它有点毛茸茸的,丑陋的,可能很危险......

相关:

You can, it's even possible to call:

delete this;

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

Related:

背叛残局 2024-08-14 15:05:44

当然:

void cleanup(){
 delete this;
}

当然,有很多事情您需要确定(其中最重要的是,如果您尝试对在堆栈上创建的实例执行此操作,则会遇到麻烦。

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.

我恋#小黄人 2024-08-14 15:05:44

是 - 删除此; 有效。只需确保这是与执行删除的函数中完成的类相关的最后一件事。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文