对象可以自毁吗? [英] Can an object destroy itself?

查看:183
本文介绍了对象可以自毁吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要摧毁自己的对象。

I have an object which needs to destroy itself.


  • 可以吗?

  • Can it be done?

示例错了?

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


推荐答案

是的,在成员函数内调用删除此是合法的。但是有很少有这样做的好理由(特别是如果你正在写惯用的C ++,大多数内存管理任务应该委托给容器,智能指针等)。

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

您需要非常


  • 必须通过 new (不是 new [] )动态分配。

  • 一旦对象自杀,它是不确定的行为,它可以做任何依赖自己的存在(它不能再访问自己的成员变量,调用自己的虚拟函数等)。

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

这篇关于对象可以自毁吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆