Can I call delete on primitives?

I have a template class myFoo that stores "stuff" of type T, which can be either primitive or a pointer to complex types. When myFoo is deleted, I want to free all the memory associated with everything that it stores. This means that I need to call delete on every saved pointer, but I can also end up calling delete on the primitive. It is safe?

I have included the myFoo sketch below to better highlight what is happening. I am not sure that the behavior of the destructor is well defined.

template<class T>
class myFoo
{
   public:
       myFoo(int size) 
       { 
          size_ = size;
          T* foo = new T[size_]; 
       }

       void addFoo(T tmp, int index) 
       {
             foo[index] = tmp;
       }

       virtual ~myFoo()
       {
           for(int i=0; i < size_; i++)
           {
               delete foo[i];
           }
           delete [] foo;
       }

  private:
      int size_;
      T* foo;
}
+5
source share
2 answers

, delete on - . , delete int. , -, , .

, , "" .

+5

template <class T> struct delete_it;

template <class T> struct delete_it<T*>
{
   static void func(T* ptr) { delete ptr; }
};

template <> struct delete_it<int>
{
   static void func(int) {}
};

template <> struct delete_it<double>
{
   static void func(double) {}
};

.

   virtual ~myFoo()
   {
       for(int i=0; i < size_; i++)
       {
           delete_it<T>::func(foo[i]);
       }
       delete [] foo;
   }

.

+1

All Articles