Can I call delete on primitives?

徘徊边缘 提交于 2019-12-05 08:44:54

The only thing you can call delete on is a pointer type. It's an error to call delete on an int, for example. If you arrange your templates so that your code tries to do something that is an error, the compiler will let you know and refuse to compile your code.

So no, you don't have to worry about "accidentally" deleting a non-pointer.

Template specialization

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

Repeat for all primitive types. Then

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

Unchecked code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!