简体   繁体   English

从堆栈上分配的对象指针向量中删除元素

[英]Deleting an element from a vector of object pointers allocated on the stack

I have a vector of Object pointers. 我有一个Object指针向量。 I want to be able to delete those objects and free the memory taken up by those objects. 我希望能够删除这些对象并释放这些对象占用的内存。

What I have currently is this: 我现在拥有的是:

This is the vector that contains the object pointers: 这是包含对象指针的向量:

std::vector<Ball*> List;

This is the function that deletes the element in the vector and frees the memory: 这是删除向量中的元素并释放内存的函数:

void BallManager::DeleteBall(int id) 
{
    List[id]->~Ball(); //Not sure if this is needed
    delete List[id];
    List[id] = NULL;
    List.erase(List.begin()+id);
}

My question is do I need to also call the destructor for the object or is that taken care of by delete? 我的问题是我是否还需要为对象调用析构函数,还是由删除处理?

If you want to delete pointer element, delete will call object destructor. 如果要删除指针元素, delete将调用对象析构函数。 No need to call List[id]->~Ball() also no need to set pointer to NULL as you are going to erase the element anyway. 无需调用List[id]->~Ball()也无需将指针设置为NULL,因为无论如何都要擦除元素。

std::vector<Ball*> List;

void BallManager::DeleteBall(int id) 
{
    if (id < List.size())   // should check id is still in range
    {  
      delete List[id];
      List.erase(List.begin()+id);
    }
}

Strongly recommand you use smart pointer as Chris mentioned, then you don't need to worry about deleting object pointer when you delete element from STL container, demo as below: 强烈建议您使用智能指针,如Chris提到的那样,当您从STL容器中删除元素时,您不必担心删除对象指针,演示如下:

  std::vector<std::shared_ptr<Ball> > List;
  void BallManager::DeleteBall(int id) 
  {
     if (id < List.size())   // should check id is still in range
     {  
        List.erase(List.begin()+id);
     }
  }

No, calling delete (as opposed to dealloc) automatically calls the destructor. 不,调用delete(而不是dealloc)会自动调用析构函数。

After deleting the element, there is no need to set it to null either, you can just erase it. 删除元素后,也不需要将其设置为空,只需擦除即可。

void BallManager::DeleteBall(int id) 
{
    delete List[id];
    List.erase(List.begin()+id);
}

new automatically calls the constructor, the corresponding delete automatically calls the destructor. new自动调用构造函数,相应的delete会自动调用析构函数。

You almost never have to explicitly call destructors. 你几乎不必明确地调用析构函数。 They are called through the deallocation process -- delete in the case of dynamically allocated objects. 它们通过释放过程调用 - 在动态分配的对象的情况下删除。

See Destructors FAQ about halfway down for more detail. 有关更多详细信息,请参阅Destructors常见问题解答

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

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