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)
{
    if(theMap.find(ID)!=theMap.end())
    {
        T2 second = theMap.find(ID)->second;
        theMap.erase(theMap.find(ID));
        //delete second; //Had to comment it out now.
        return true;
    }
    return false;
}

      

+3


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;}

      


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

  delete_or_nop (p);
  delete_or_nop (n);
}

      

+5


source


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.



+8


source


    template<class T>
    class Pointer
    {
        private:
       T* pointer;
       int* ref;


    public:
    Pointer():pointer(0), ref(0)
    {
    ๏ผˆ*ref๏ผ‰++;

    }

    Pointer(T* value):pointer(value),reference(0)
    {
    ๏ผˆ*ref)++;

    }

    Pointer(const pointer<T>& sp):pointer(sp.pointer),ref(sp.ref)
    {
       (*ref)++;
    }

    ~Pointer()
    {
   if(--(*ref)==0)
     {delete pointer;
       delete ref;
     }
    }
    };

      

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

0


source







All Articles