Delete a C++ list of pointers like a boss

Tired of iterating to delete a C++ list of pointers? C++11 lambda functions can help you!

#include <iostream>
#include <list>

int
main(void)
{
  std::list<std::string *> lst;

  lst.push_back(new std::string("foo"));
  lst.push_back(new std::string("bar"));
  lst.push_back(new std::string("baz"));

  std::cout << lst.size() << " elems." << std::endl;

  lst.remove_if([](std::string *elem)->bool {
      delete elem;
      return true;
    });

  std::cout << lst.size() << " elems." << std::endl;

  return 0;
}

valgrind is happy:

==16340== HEAP SUMMARY:
==16340==     in use at exit: 0 bytes in 0 blocks
==16340==   total heap usage: 9 allocs, 9 frees, 180 bytes allocated
==16340== 
==16340== All heap blocks were freed -- no leaks are possible

Requirements

Your C++ compiler needs to support lambda functions, which have been introduced in C++11. GCC supports it since GCC 4.5.

Tags