Luke Cauthen
Luke Cauthen

Reputation: 730

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

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?

Upvotes: 2

Views: 6608

Answers (3)

billz
billz

Reputation: 45410

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

Upvotes: 2

Ryan Guthrie
Ryan Guthrie

Reputation: 688

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.

Upvotes: 1

iagreen
iagreen

Reputation: 32016

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.

Upvotes: 0

Related Questions