Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an object destroy itself?

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;
    }
    
like image 361
danjjl Avatar asked Mar 25 '12 21:03

danjjl


People also ask

Can an object delete itself JS?

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.

How do you make an object destroy itself in Java?

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.

Can a class delete itself C++?

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.

How do you destroy another object in unity?

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.


1 Answers

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:

  • the suicide object must have been allocated dynamically via new (not new[]).
  • once an object has committed suicide, it is undefined behaviour for it to do anything that relies on its own existence (it can no longer access its own member variables, call its own virtual functions, etc.).
like image 74
Oliver Charlesworth Avatar answered Oct 05 '22 19:10

Oliver Charlesworth