Deleting Pointers

Posted by Nick Gammon on Wed 02 Jul 2003 06:34 AM — 1 posts, 6,708 views.

Australia Forum Administrator #0
If you have a container of pointers you cannot just remove the elements from the container, you also need to delete the data the pointers are pointing to (presumably). Here is a nifty way of doing that ...


struct DeleteObject
  {
  template <typename T>
  void operator() (const T* ptr) const { delete ptr; };
  };


You can these use this in a for_each statement. Here is an example ...



#include <string>
#include <list>
#include <algorithm>

using namespace std;

struct DeleteObject
  {
  template <typename T>
  void operator() (const T* ptr) const { delete ptr; };
  };

class Person
  {
  public:

    // constructor
    Person (const string sName, 
            const string sEmail, 
            const int iAge) :
    m_sName (sName), m_sEmail (sEmail), m_iAge (iAge) {};

  string m_sName;
  string m_sEmail;
  int    m_iAge;
  };

typedef list<Person*> PersonList;

int main (void)
  {
  PersonList people;

  // add items to list
  people.push_back (new Person ("Nick", "nick@some-email-address.com", 15));
  people.push_back (new Person ("Fred", "fred@nurk.com.au", 100));

  // delete all objects in list
  for_each (people.begin (), people.end (), DeleteObject ());
  // now delete them from the list
  people.clear ();

  return 0;
  } // end of main



The DeleteObject function is a template so it automatically deletes the right sort of object.