If I have a STL container that takes object pointers as elements, I will need to delete the pointers in the destructor of the class that has such a container. Since the operation of deleting a pointer
delete ptr_;
ptr_ = 0;
might be often used, I wonder if there is a function (or function object) template that does this, defined in boost, or STL or by the standard somewhere as the function object DeletePointer defined in the following example:
#include <list>
#include <algorithm>
template<class Pointer>
class DeletePointer
{
public:
void operator()(Pointer t)
{
delete t;
t = 0;
}
};
using namespace std;
int main()
{
list<double*> doublePtrList;
doublePtrList.push_back(new double (0));
doublePtrList.push_back(new double (1));
doublePtrList.push_back(new double (2));
doublePtrList.push_back(new double (3));
for_each(doublePtrList.begin(), doublePtrList.end(), DeletePointer<double*>());
};
If (for some reason) you can’t store smart pointers instead of raw pointers in your collection, consider using a Boost pointer container instead.