I have an object which needs to destroy itself.
Can it be done?
Is the example wrong?
void Pawn::specialMoves(Coordinate const& from, Coordinate const& to, int passant)
{
/*...*/
m_board->replace(to, new Queen(m_colour));//replace pawn by queen
}
void Board::replace(Coordinate const &to, Piece* newPiece)
{
delete tile[to.x()][to.y()];
tile[to.x()][to.y()] = newPiece;
}
No. this is just a local reference to the object so deleting it does not make the object not exist. There is no way for an object to self destruct in this manner.
Since an object cannot determine how many references there are to itself, an object cannot "destroy itself". Show activity on this post. The object doesn't have access to the references to it so there's no way to set them to null or something else.
No. Just no! Allocate the dialog to the stack and make ui a smart pointer ( std::unique_ptr ). As a side note, normally dialogs are closed by calling either accept() or reject() not by deleting itself.
Destroying the main object that collide with other objects For 2D games you need the void OnCollisionEnter2D() method and the void OnCollisionEnter() method for 3D games. Both of these methods will activate when the object that the script is attached to has a collider and collides with an object.
Yes, it's legal to call delete this
from inside a member function. But there's very rarely a good reason to do so (especially if you're writing idiomatic C++ where most memory-management tasks should be delegated to containers, smart pointers, etc.).
And you need to be very careful:
new
(not new[]
).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With