Search code examples
c++objectdestroy

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;
    }
    

Solution

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