Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 774
sonicbhoc Avatar asked Feb 15 '26 14:02

sonicbhoc


2 Answers

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

like image 70
Igor Avatar answered Feb 17 '26 04:02

Igor


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?
like image 25
Jesper Avatar answered Feb 17 '26 02:02

Jesper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!