Technology

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):

template
struct deleter: public std::unary_function
{
    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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.