F. Aydemir
F. Aydemir

Reputation: 2735

std::vector Erase - does it de-allocate automatically?

In below code mKnownRSList is of type:

  std::vector<RSAddress *> 

where RSAddress is a class I wrote. The functiop removeItem removes an item from this vector.

My question here is that after calling the erase function on mKnownRSList, am I supposed to de-allocate the address pointed by the iterator returned by std::remove_if. Currently I explicitly issue a delete call on the de-referenced iterator named last. Do you think this approach is correct? Thanks.

void 
ABC::removeItem(RSAddress * rsAddr)
{
   auto last = 
   std::remove_if(mKnownRSList.begin(),
                  mKnownRSList.end(),
                 [rsAddr]( RSAddress * o )
                 {
                   return (*o == *rsAddr);
                 });

 mKnownRSList.erase(last, mKnownRSList.end());

 delete *last;
}

Upvotes: 0

Views: 165

Answers (2)

borisbn
borisbn

Reputation: 5054

Do you think this approach is correct?

Nope. The correct way is to use smart_pointers like shared_ptr. If you will, then you should only erase it. like this

std::vector< std::shared_ptr< RSAddress  > > mKnownRSList;
...

mKnownRSList.erase( std::remove_if(mKnownRSList.begin(),
                                   mKnownRSList.end(),
                                   [rsAddr]( const std::shared_ptr< RSAddress > & o )
                                   {
                                       return (*o == *rsAddr);
                                   }),
                    mKnownRSList.end()
);

Upvotes: 1

Tony The Lion
Tony The Lion

Reputation: 63190

You should delete what is pointed to by your pointer inside the container first and then you remove/erase the actual pointer from the container.

What you're doing here is dereferencing an iterator that points to something that no longer exists.

Upvotes: 3

Related Questions