Functor for deleting objects

In a destructor for a class, I had a std::vector of pointers that I wanted to delete. I started to write the usual for(;;) loop and realized I do this often enough I should make it easy to use std::for_each().

Here’s the functor (based on std::unary_function):

    #include 

template<typename Type>
struct deleter: public std::unary_function<Type *, bool>
{
bool operator()(Type * ptr) const
{
    delete ptr;
    return true;
}
};

And here’s some sample code using it:

std::vector m_symbols;
// ...
std::for_each (m_symbols.begin(), m_symbols.end(), deleter());

I added a return of true because some other template code wasn’t happy about “return void” — supposedly something fixed in recent compilers.

Tags: ,