tmaric
tmaric

Reputation: 5477

Is there a function (object) template for pointer deletion available for re-use somewhere (boost, STL)?

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*>());
};

Upvotes: 1

Views: 126

Answers (3)

Roee Gavirel
Roee Gavirel

Reputation: 19443

just use shared pointers of std:

include <memory>

using namespace std;

int main()
{
    list<shared_ptr<double>> doublePtrList;

    doublePtrList.push_back(make_shared<double>(0.0));
    doublePtrList.push_back(make_shared<double>(1.0));
    doublePtrList.push_back(make_shared<double>(2.0));
    doublePtrList.push_back(make_shared<double>(3.0));

    //for_each(doublePtrList.begin(), doublePtrList.end(), DeletePointer<double*>());

    //For clearing just clear the list
    doublePtrList.clear();
};

shared pointers automatically free delete the memory when no one reference it (or to be more correct when the last reference stop referencing it)

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490178

If (for some reason) you can't store smart pointers instead of raw pointers in your collection, consider using a Boost pointer container instead.

Upvotes: 3

As others have suggested, it's a good idea to use a smart pointer instead of raw pointers whenever possible.

However, to directly answer your question, there is std::default_delete defined in <memory> (in C++11).

Upvotes: 1

Related Questions