Reclaiming memory with templates

Most of the time when using STL containers in C++, you want to use them with pointers to preserve run-time polymorphic behaviour. For example, a list of strings would be defined as

std::list<std::string> myStrings;

The only problem with this is that you need to remember to call delete on every element in that list before myStrings goes out of scope. That’s not a big problem you may argue, just iterate trough the whole list and delete them.

std::list<std::string *>::iterator it = myStrings.begin();
std::list<std::string *>::const_iterator end = myStrings.end();
while (it != end) delete *it++;

But when you have many containers with pointers, this duplication of code tends to become tedious. This is where templates and for_each comes into play. Add the following code to a header filer.

/// A function with the sole purpose of deleting @a ptr
template<typename T>
inline void deletePtr(const T& ptr) { delete ptr; }
 
/// Calls delete on every element in @a container
template<typename T>
inline void deleteAllPtr(const T& container)
{
  std::for_each(container.begin(), container.end(),
                deletePtr<typename T::value_type>);
}

Then, when you wish to delete a container with pointers, just include the header file and call

deleteAllPtr(myStrings);

Simply beautiful :)

Posted Friday, February 24th, 2006 under programming.

Tags:

Comments are closed.