我可以在原语上调用delete吗? [英] Can I call delete on primitives?

查看:85
本文介绍了我可以在原语上调用delete吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模板化类myFoo,它存储类型T的东西,它可以是原始的也可以是指向复杂类型的指针。删除myFoo后,我想释放与其碰巧要存储的所有内容相关的所有内存。这意味着我需要在存储的每个指针上调用delete,但是我可能最终还会在原语上调用delete。这样安全吗?

I have a templated class, myFoo, which stores "stuff" of type T which can be either primitive or pointers to complex types. When myFoo is deleted, I want to release all the memory associated with everything it happens to be storing. This means I need to call delete on every pointer being stored but I might also end up calling delete on a primitive. Is this safe??

我在下面添加了myFoo的草图,以更好地说明发生了什么。我不确定析构函数的行为是否定义正确。

I've included a sketch of myFoo below to better highlight what's going on. I'm not sure if the behaviour 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;
}


推荐答案

唯一可以调用的东西 delete on是指针类型。例如,在 int 上调用 delete 是错误的。如果您安排模板以使您的代码尝试执行错误操作,则编译器将告知您并拒绝编译您的代码。

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.

这篇关于我可以在原语上调用delete吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆