1
votes

I have a vector of Object pointers. 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?

3
I highly recommend a vector of smart pointers instead. You won't need to worry about managing the pointer's memory if you do; simply calling erase would deallocate the memory and everything as well. - chris

3 Answers

2
votes

If you want to delete pointer element, delete will call object destructor. No need to call List[id]->~Ball() also no need to set pointer to NULL as you are going to erase the element anyway.

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:

  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);
     }
  }
1
votes

No, calling delete (as opposed to dealloc) automatically calls the destructor.

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.

0
votes

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.