ARTcrime
ARTcrime

Reputation: 110

Deleting elements out of vector of pointer

I'm trying to delete elements in a vector. This works so far, but the I can't free the deleted memory.

The Code I use:

vector<TJet*> *tlv_jets;
//...Filling tlv_jets...
for (vector<TJet*>::iterator it = tlv_jets->begin(); it != tlv_jets->end();/*it++*/)
    {
    if (TMath::Abs((*it)->Rapidity()) > ycut)
        {
        cout<< "================" << endl;
        cout<< (*it)->Rapidity() << endl; //Check before deleting
        delete *it;                       //free memory
        cout<< (*it)->Rapidity() << endl; //Check after deleting
        it = tlv_jets->erase(it);         //remove from vector

     }
    else
        ++it;
     }

Inside the if is simply the selection of the elements I want to delete. Both couts return the same value, but I expected a seg fault as I'm trying to access a deleted object. Instead, I run into memory problems as I do not free the memory of the deleted objects correctly. Where does it go wrong?

Thanks!

Upvotes: 1

Views: 92

Answers (3)

Dimitrios Bouzas
Dimitrios Bouzas

Reputation: 42929

As a complementary answer, if your compiler supports C++11 you could do this in one line:

tlv_jets->erase(std::remove_if(std::begin(*tlv_jets),
                              std::end(  *tlv_jets), 
                              [&] (TJet* e) {
                                if(TMath::Abs(e->Rapidity()) > ycut) {
                                  delete e;
                                  return true;
                                }
                                return false;
                              }), std::end(tlv_jets));

Upvotes: 0

herolover
herolover

Reputation: 803

It depends on the TJet::Rapidity content. If there are not any treatments inside this method to TJet members, then won't an error.

Upvotes: 0

James Kanze
James Kanze

Reputation: 154047

Accessing the deleted object is undefined behavior. There's no guarantee of a segfault, or anything else. The delete *it should free up the memory correctly, but following undefined behavior, all bets are off. (What does TJet::Rapidity do, for example. Calling it on a destructed object could result in corruption of the free space arena, for example.)

Do you still have a problem when you remove the second check?

Also, for what it's worth (but I wouldn't worry about it):

The delete *it is formally undefined behavior too, since it results in an uncopyable object in the vector. Formally, of course. In practice, it's very, very rare for the copy of a deleted pointer to actually cause any problems, and even if it does, no implementation of vector will actually copy the deleted pointer, since it will be overwritten by the erase (without first being copied).

Upvotes: 1

Related Questions