简体   繁体   中英

How can I delete this object I created?

Take this program as an example:

class Piece
{
public:
    Piece(bool color);

protected:
    bool color;
};

Piece::Piece(bool color)
{
    this->color = color;
}

//-----------------------------

class King : public Piece
{
public:
    King(bool color);
};

King::King(bool color) : Piece(color)
{
    // empty
}

//-----------------------------

class Tile
{
public:
    // constructors/destructors
    Tile(Piece * ppiece, int rrow, int ccol);
    ~Tile();

private:
    Piece * piece;
    int row, col;

};

Tile::Tile(Piece * ppiece, int rrow, int ccol)
{
    this->ppiece = piece;
    this->row = rrow;
    this->col = ccol;
}

//---------------------------

int main() 
{
    Tile * tile = new Tile(new King(0), 1, 1);
}

In the function main() I declare a new King and pass it to the Tile constructor. How can I delete the King object I created?

As written, the Tile Constructor receives the new King as parameter ppiece .

The Tile Constructor then doesn't do anything with ppiece, and the memory is cannot be freed. It is "leaked".

Given that Tile has a member piece , I'd suggest assigning it there:

Tile::Tile(Piece * ppiece, int rrow, int ccol)
{
    this->row = rrow;
    this->col = ccol;
    this->piece = ppiece;
}

Then you can later free it in the Tile destructor:

Tile::~Tile()
{
    delete piece;
}

There are several good answers already, but I thought I'd at least mention this... The topic may be too advanced for you at the moment, but at some point it's definitely worth learning about "smart" pointers. Boost::shared_ptr is a good place to start. Also std::unique_ptr.

I would recommend keeping all of the pieces in their own array outside of the Tile set, creating and deleting them at the same level.

However, if that is impossible. I would say delete it if the piece is removed from the tiles.

Also, have a function that clears your tile set, that iterates through and deletes the pieces on that tile.

You could also make it part of ~Tile(), but I personally dislike creating/deleting at different levels.

If you go with the destructor, be careful about keeping pointers to the piece outside of the Tile.

There really is no need to use new and delete in the first place (C++ isn't Java). You can treat the class objects as values, much like you do with an int .

class Tile
{
public:
    // constructors/destructors
    Tile(Piece ppiece, int rrow, int ccol);
    ~Tile();

private:
    Piece piece;
    int row, col;

};

Tile::Tile(Piece ppiece, int rrow, int ccol)
{
    this->ppiece = piece;
    this->row = rrow;
    this->col = ccol;
}

//---------------------------

int main() 
{
    Tile tile(King(0), 1, 1);
}

No new , no delete , no problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM