简体   繁体   English

C ++删除对象

[英]C++ deleting an object

Does the delete() operator destroy all the sub-objects of an object too? delete()运算符也会破坏对象的所有子对象吗? Or do I need to call the delete of sub-object before deleting the parent object? 还是在删除父对象之前需要调用子对象的删除?

class equipment
{
   public:
     int model_id;
     ...
}

class player
{
   public:
     int x, y;
     equipment * Equipment; 
     player(void) { Equipment = new equipment[2];};
     ~player(void) { delete [] Equipment; }
};

int main (....)
{
  player = new Player;
  ...
  ...
  delete Player;
}

您需要在主对象的析构函数中删除动态分配的子对象,并且已通过删除数组Equipment正确地完成了此操作

Delete operator does delete all "subobjects" as you say, but usually and in your case you need to delete not only "sub objects" but also memory, where member pointers point to. 删除运算符确实会删除您所说的所有“子对象”,但是通常,在这种情况下,您不仅需要删除“子对象”,还需要删除成员指针指向的内存。 So if you used vector object, for example, it would be deleted automatically, but in this case you need to delete it explicitly, which you did correctly 因此,例如,如果使用矢量对象,它将被自动删除,但是在这种情况下,您需要显式删除它,这是正确的

To put it simply, during destruction of the object : 简而言之,在销毁对象期间:

  • Member objects are themselves destroyed 成员对象本身被销毁
  • Objects pointed by member pointers aren't 成员指针指向的对象不是

That means that you have to delete them manually (like your Equipement pointer), if you own them . 这意味着, 如果您拥有它们则必须手动删除它们(如Equipement指针)。 There might be case when your class ends up with a pointer it does not own (for example, a handle to some other object you need in this class), and thus should not delete. 在某些情况下,您的类可能以其不拥有的指针结尾(例如,该类中您需要的其他对象的句柄),因此不应删除。

You can use smart pointers (ie: std::shared_ptr , std::unique_ptr , etc.) to manage memory in a safer way (they, notably, automatically delete the pointers they manage, following the RAII principle ). 您可以使用智能指针(即std::shared_ptrstd::unique_ptr等)以更安全的方式管理内存(值得注意的是,它们会遵循RAII原理自动删除它们管理的指针)。

您缺少的一件事是一流设备中的析构函数

The stuff you do in your example is sufficient, you 您在示例中所做的事情就足够了,您

delete[] Equipment;

in the destructor of player, so all contained equipments will be deleted as soon as a player gets deleted. 在播放器的析构函数中,因此删除播放器后,所有包含的设备都将被删除。

Nicely done! 做得很好!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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