Is there any standard delete functor?
Asked Answered
B

3

6

I am looking for a functor that deletes its argument:

template<class T>
struct delete_functor
{
    void operator()(T* p)
    {
        delete p;
    }
};

Is there something like this in std, tr1 or boost?

Bullyrag answered 27/4, 2010 at 19:33 Comment(1)
If you were writing this yourself, btw, then with struct delete_functor { template <typename T> void operator()(T* p) { delete p; } };, you don't have to specify T when you create one.Microseism
O
10

C++0x will add std::default_delete to the standard library to support std::unique_ptr.

It has effectively the same functionality as your delete_functor, but is also specialized to call delete[] for array type objects.

Oakie answered 27/4, 2010 at 19:34 Comment(4)
What does std::default_delete<void>() do?Chloral
@user1095108: If the operator() is instantiated, the program would be ill-formed. The type with which default_delete is instantiated may be incomplete at the time the class template is instantiated, but it must be complete when the operator() is instantiated.Oakie
@JamesMcNellis So one must instantiate std::unique_ptr<void, void(*)(void*)> p{ 0, operator delete }; to delete void* correctly?Chloral
@user1095108: The operand of delete may not be a void*. If you attempt to delete a void*, the program is ill-formed.Oakie
H
2

Boost.Lambda has delete_ptr and delete_array

Hefner answered 27/4, 2010 at 19:39 Comment(1)
#include <boost/lambda/construct.hpp>Plummer
A
0

We are not allowed to use boost in my company, and we're not using C++11 either, so I use this:

namespace
{
  // - for use to deletion:
  // std::vector<int*> foobar;
  // std::for_each(foobar.begin(), fooabr.end(), del_fun<T>());
  template<class _Type>
  struct del_fun_t:
    public unary_function<_Type*, void>
  {
    void operator()(_Type* __ptr) {
      delete __ptr;
    }
  };

  template<class _Type>
  del_fun_t<_Type> del_fun()
  {
    return del_fun_t<_Type>();
  };
};

I think that's what you're looking for.

You can also recreate it as dtor_fun_t and replace "delete _ptr;" by "_ptr->~_Type();" to only call the dtor. This would be the case where you used a memory manager and placement new for example.

Aleida answered 23/5, 2012 at 15:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.