user1274605
user1274605

Reputation: 405

std::list of pointers and remove_if

I'm doing some tests with a std::list of pointers. I'm using remove_if algorithm to eliminate some elements of the list. But I encountered some problems, remove_if is creating memory leaks because it doesn't destroy the pointers (I think).

I found a solution, but I don't know if it is well made, correct or at least acceptable...

Here is the code:

#include <algorithm>
#include <iostream>
#include <list>

using namespace std;

class Object
{
 private:
         int intData;   
 public:
        Object(int n) : intData(n) { };
        int getIntData(void) { return intData; };
        void setIntData(int n) { intData = n; };
};

/** Functor */
struct listFunctor
{ 
 bool operator()(Object* obj1, Object* obj2) const
 {
  return (obj1->getIntData() < obj2->getIntData());
 }
};

class removeFunctor
{
 private:
         int remover;
 public:
        removeFunctor(int n) : remover(n) { };
        bool operator()(Object* obj)
        {
         bool res = (obj->getIntData() != remover);

         if(res)
          delete obj;

         return res; 
        }
};

typedef list<Object*> objList;
typedef list<Object*>::iterator objectListIter;

int main(int argc, char** argv)
{
 objList objectList;

 objectList.push_back(new Object(8));
 objectList.push_back(new Object(0));
 objectList.push_back(new Object(2));

 /** sort elements. */
 objectList.sort(listFunctor());

 /** print. */
 for(objectListIter it = objectList.begin(); it != objectList.end(); ++it)
  cout<<*it<<"  "<<(*it)->getIntData()<<'\n';   

 /** remove. */
 objectListIter iter = remove_if(objectList.begin(), objectList.end(), removeFunctor(8));

 /** print. */
 for(objectListIter it = objectList.begin(); it != iter; ++it)
  cout<<*it<<"  "<<(*it)->getIntData()<<'\n';   

 /** delete list. */
 for(objectListIter it = objectList.begin(); it != iter; ++it)
  delete *it;   

 objectList.clear(); //IS THIS NECESSARY?

 return 0;
}

The program first creates the list, sort it an then removes some elements.

Is this code a good and viable solution to this problem? Valgrind's default scan doesn't report any problems but I'm doing more tests.

Thanks.

Upvotes: 2

Views: 1967

Answers (1)

Benj
Benj

Reputation: 32398

Removing from a list<Object*> will only remove the pointers from the list. You should prefer a list<unique_ptr<Object>> or a list<shared_ptr<Object>> which will automatically delete the objects pointed to when the smart pointers are removed from the list.

Upvotes: 11

Related Questions