Click here to Skip to main content
15,881,516 members
Articles / Programming Languages / C++

A Functor that deletes Pointers from STL Sequence Containers

Rate me:
Please Sign up or sign in to vote.
4.48/5 (18 votes)
21 Mar 2004BSD4 min read 72K   679   16  
A policy based deletion functor that can be used with for_each function.
#include <vector>
#include <algorithm>
#include "FreePtr.h"
using namespace std;
using namespace FreePtr;


class C
    {
    char* data_;
    public:
        C()
            {
            data_ = new char[512];
            }
        ~C()
            {
            delete[] data_;
            }
    };



int main ()
    {
    vector <C*> objects;
    for (int i = 0; i < 20; ++i)
        objects.push_back(new C());
    for_each(objects.begin(), objects.end(), free_ptr<C>());
    objects.clear();

    for (int i = 0; i < 20; ++i)
        objects.push_back(new C[10]);
    for_each(objects.begin(), objects.end(), free_ptr<C, DeleteArray, ZeroPtr>());
    objects.clear();

    for (int i = 0; i < 20; ++i)
        objects.push_back((C*)malloc(sizeof(C)));
    for_each(objects.begin(), objects.end(), free_ptr<C, Free>());
    objects.clear();
    }

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The BSD License


Written By
Software Developer (Senior)
United States United States
Born in Kragujevac, Serbia. Now lives in Boston area with his wife and daughters.

Wrote his first program at the age of 13 on a Sinclair Spectrum, became a professional software developer after he graduated.

Very passionate about programming and software development in general.

Comments and Discussions