The call is removed only if the value is a pointer

I am creating a class that adds some basic operations to std :: map, and I would like to automatically call delete after removing an item from the map. But if the second (T2) value is not a pointer, this is not possible. Is there a way to check?

template <class T,class T2>
bool CExtendedMap<T,T2>::remove(T ID)
        T2 second = theMap.find(ID)->second;
        //delete second; //Had to comment it out now.
        return true;
    return false;



source to share

3 answers

If I understand your question correctly, you would like to behave differently if the value of the paired memory stored in yours CExtendedMap

is or is not a pointer.

One of the easy ways to solve this problem is to use boilerplate overloads to get the desired effect.

Implement a wrapper function that will use delete

if the parameter is a pointer, or do nothing if it isn't, which is actually the simplest solution.

Below is an example implementation:

template<class T> inline
void delete_or_nop (T  const&)    {/* NOP */}

template<class T> inline
void delete_or_nop (T* const& p)  {delete p;}


main (int argc, char *argv[])
  int * p = 0;
  int   n = 0;

  delete_or_nop (p);
  delete_or_nop (n);




Use smart pointers instead, so you don't have to worry about deleting anything. The memory will be freed when you erase

item from the card.



    template<class T>
    class Pointer
       T* pointer;
       int* ref;

    Pointer():pointer(0), ref(0)


    Pointer(T* value):pointer(value),reference(0)


    Pointer(const pointer<T>& sp):pointer(sp.pointer),ref(sp.ref)

     {delete pointer;
       delete ref;


There are some operators like โ†’, *, = that need to be overridden.



All Articles