Click here to Skip to main content
13,550,709 members
Click here to Skip to main content
Add your own
alternative version


16 bookmarked
Posted 21 Mar 2004
Licenced BSD

A Functor that deletes Pointers from STL Sequence Containers

, 21 Mar 2004
Rate this:
Please Sign up or sign in to vote.
A policy based deletion functor that can be used with for_each function.


A great thing about STL containers is the way they automatically handle memory for us. By using standard sequence containers such as vector or deque instead of directly dealing with operators new[] and delete[], we avoid possibilities of memory leaks and make our code exception-safe. For instance, if we need a dynamic array of integers within a function, if we use std::vector<int> rather than int*, we would be relieved from worrying about calling delete to free up the memory before we exit the function:

vector<int> vectorArray (30); // the memory will be automatically freed
int* oldStyleArray = new int[30]; // be sure to call delete[] oldStyleArray;

However, things get more complicated if we put pointers into a standard container:

struct C
  char data_[50];
  vector <C*> dataArray;
for (int i = 0; i < 20 ; ++i)
  dataArray.push_back(new C());

After dataArray goes out of scope, only the memory occupied by the pointers itself will be freed, but the objects themselves will stay undeleted unless we do something like:

for (vector <C*>::iterator it = dataArray.begin(), 
  it != dataArray.end(); ++it)
  delete *it;

before dataArray goes out of scope.

The best way to deal with this issue is to never put raw pointers into containers, but to use smart pointers, such as boost::shared_ptr [1], or Loki::SmartPtr [2]:

vector <boost::shared_ptr<C> > dataArray;
for (int i = 0; i < 20 ; ++i)
  dataArray.push_back(boost::shared_ptr<C> (new C()));

Now, we won’t need to care about freeing up the objects.

However, in some instances we still may want to keep raw pointers in STL sequence containers, and in that case we may use some easier way to clean up the memory than hand-writing the loop. One common solution is to write a functor that would give us possibility of using an STL algorithm such as for_each [3].

for_each(dataArray.begin(), dataArray.end(), del_fun<C>());

This approach is better, but it still leaves a lot to be desired. For one thing, it always calls operator delete, which is not appropriate for the cases where the objects are created with new[] or malloc. Also, in some cases we may want to zero the pointers after we delete them.

To address these issues, I implemented a policy-based functor free_ptr.

Design of free_ptr

When using a functor for deleting objects, we are faced with two orthogonal decisions:

  1. Which function to use for deleting objects?
  2. Do we zero the pointers after deletions?

To give the user a choice to make the decisions, I used two separate policies: CleanUpPolicy and ZeroPtrPolicy:

template <typename T, class CleanUpPolicy = DeleteSingleObject, class 
ZeroPtrPolicy = DontZeroPtr>
struct free_ptr : std::unary_function <T*, void>
  void operator()(T*& ptr)

Thanks to the policy-based design, free_ptr is very simple to use, and yet highly customizable. For the most common scenario (single objects created with new, no need to zero pointers), it can be used like this:

for_each(dataArray.begin(), dataArray.end(), free_ptr<C>());

If the objects were created with new[], and we need to zero the pointers after deletion, we write something like:

for_each(dataArray.begin(), dataArray.end(), free_ptr<C, DeleteArray, 

For the CleanUpPolicy, we have the following choices:

  1. DeleteSingleObject (default) – calls delete for each pointer.
  2. DeleteArray – calls delete[] for each pointer.
  3. Free – calls free() for each pointer.

For the ZeroPtrPolicy, we have two choices:

  1. DontZeroPtr (default) – does nothing.
  2. ZeroPtr - sets each pointer to zero.

In ideal world, we would not even need CleanUpPolicy – if a pointer to a single object was a distinct type than a pointer to array of objects we could have used some template metaprogramming to recognize the right scenario at compile time. However, since this obviously is not the case, I tried to figure out some run-time mechanism to do that. I failed miserably: there does not seem to be a good way to distinguish whether a memory was allocated by new, new[] or malloc if we only have a pointer to this memory. I tried even some non-portable tricks, such as using _memsize to determine the size of the allocated memory block, however, even if we know the amount of allocated memory, it still does not necessarily shows us the number of objects pointed by the pointer. Therefore, the best I could come up with was CleanUpPolicy. One good thing with this solution is that in case of some custom memory-management schema, it would be very easy to write another CleanUpPolicy class and use it as easily as the ones I provided.

I should probably add that usage of free_ptr will not protect you from some bad programming practices. For instance, if you do something like:

vector <C*> dataArray;
dataArray.push_back(new C()); //single object

dataArray.push_back(new C[10]); //array of objects

dataArray.push_back((C*)malloc(sizeof(C))); // malloc-ed object

then free_ptr will not help you. As I said, it is unfortunate that the previous example will compile at all, but this is just another C-legacy that makes C++ less perfect.


I hope that this little article is useful in two ways: it demonstrates policy-based design, a powerful methodology for developing C++ libraries, and it also provides you with a cool little piece of code that you can find useful in your daily programming tasks.



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


About the Author

Nemanja Trifunovic
Software Developer (Senior) SAP
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.

You may also be interested in...

Comments and Discussions

GeneralPrint version of article broken Pin
Mike Rizzi17-Jul-06 8:14
memberMike Rizzi17-Jul-06 8:14 
GeneralRe: Print version of article broken Pin
Nemanja Trifunovic17-Jul-06 9:16
memberNemanja Trifunovic17-Jul-06 9:16 
GeneralSmall bug with for_each Pin
msalters15-Apr-04 22:27
membermsalters15-Apr-04 22:27 
GeneralRe: Small bug with for_each Pin
Nemanja Trifunovic16-Apr-04 4:52
memberNemanja Trifunovic16-Apr-04 4:52 
GeneralRe: Small bug with for_each Pin
iain_22-Apr-04 2:58
sussiain_22-Apr-04 2:58 
Questiontogether with Effective STL? Pin
seriema2-Apr-04 14:27
memberseriema2-Apr-04 14:27 
AnswerRe: together with Effective STL? Pin
Nemanja Trifunovic4-Apr-04 10:24
memberNemanja Trifunovic4-Apr-04 10:24 
GeneralSolution that allows map Pin
Summand25-Mar-04 10:46
memberSummand25-Mar-04 10:46 

With you code it is not possible to use the deletor for std::map because the value_type is a std::pair.

The solution is to create a partial specialisation of your class template. Please note, that VS6 and VS7 don't support partial template specialisation. So you have to use VC7.1 for this to work.

// I removed the * from the template. This change makes it easier to use.
template < typename T, class CleanUpPolicy = DeleteSingleObject, class ZeroPtrPolicy = DontZeroPtr >
struct free_ptr : std::unary_function <T, void>
void operator()(T& ptr)

// Partial specialisation that uses std::pair
template<typename T1, typename T2, class CleanUpPolicy, class ZeroPtrPolicy>
struct free_ptr<std::pair<T1, T2>, CleanUpPolicy, ZeroPtrPolicy> : std::unary_function <std::pair<T1, T2>, void>
void operator()(std::pair<T1, T2>& ptr)

// I added the next template, because it was a pain to type free_ptr<std::pair<...> > (map::value_type isn't much better Wink | ;-) )

template<class Container>
inline free_ptr<typename Container::value_type> make_free_ptr(Container const&)
return free_ptr<typename Container::value_type>();

// Usage is now this way:

vector <int* > dataArray;
for_each(dataArray.begin(), dataArray.end(), make_free_ptr(dataArray));

map<string, int*> dataMap;
// ...
for_each(dataMap.begin(), dataMap.end(), make_free_ptr(dataMap));

GeneralRe: Solution that allows map Pin
Nemanja Trifunovic25-Mar-04 11:05
memberNemanja Trifunovic25-Mar-04 11:05 
GeneralRe: Solution that allows map Pin
Summand26-Mar-04 0:09
memberSummand26-Mar-04 0:09 
GeneralRe: Solution that allows map Pin
Simon Hughes28-Mar-04 21:48
memberSimon Hughes28-Mar-04 21:48 
GeneralI don't agree with your policy. Pin
WREY24-Mar-04 6:35
memberWREY24-Mar-04 6:35 
GeneralRe: I don't agree with your policy. Pin
Nemanja Trifunovic24-Mar-04 7:13
memberNemanja Trifunovic24-Mar-04 7:13 
GeneralFlexibility wins out !! Pin
WREY24-Mar-04 9:41
memberWREY24-Mar-04 9:41 
GeneralNice demonstration of policies Pin
thought23-Mar-04 22:20
memberthought23-Mar-04 22:20 
GeneralRe: Nice demonstration of policies Pin
Nemanja Trifunovic24-Mar-04 5:05
memberNemanja Trifunovic24-Mar-04 5:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.180515.1 | Last Updated 22 Mar 2004
Article Copyright 2004 by Nemanja Trifunovic
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid