Alex Rivera | Logout

Delete any container using templates

Asked 2010-12-18T18:20:52.377
9

I have a lot of code where I am deleting vector containers that have pointers in them, that is, I have to delete all the pointers first and then clear the container. Every time I would iterate through and delete the pointers manually (I am aware of stl::algorithms for_each). To circumvent all that code, I created a template for deleting all vector containers that have a pointer. So far so good.

Now I have several more container types including maps, concurrent containers etc. all with the same functionality in the end as far as deletion goes. The DeleteContainer(std::vector<T*>& VecIn) function that I have can only work on vectors as mentioned above. Is there any way to make it generic enough to work on all containers?

EDIT: Thanks for all the answers, I wish I could select more than one. To anybody who stumbles onto this question, read all the answers and not just the selected one as they all provide great info.

Edit
Report

2 Answers

4

You could use boost pointer containers.
They hold maintain and delete pointers correctly.

http://www.boost.org/doc/libs/1_38_0/libs/ptr_container/doc/reference.html

{
    boost::ptr_vector<int>   data;

    data.push_back(new int(2));
    data.push_back(new int(2));
    data.push_back(new int(2));
}
// container deleted and all pointers correctly destroyed.
answered 2010-12-18T18:34:54.413
0

My take on this would be:

template<class T>
void Destroy(T *p)
{
  delete p;
}

template<template<typename, typename> class C, typename T1, typename T2>
void Destroy(C<T1 *, T2> &c)
{                                                        
  std::for_each(c.begin(), c.end(), Destroy<T1>);
}

Tested on g++ 4.4.4 with vector, deque and list. You may need additional overloads of void Destroy(C<T1 *, T2> &c) for other containers and/or other STL implementations.

answered 2010-12-18T21:10:32.037

Your Answer