C / C ++删除与删除[] [英] C/C++ delete vs delete[]

查看:72
本文介绍了C / C ++删除与删除[]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:





删除与删除[]

我刚刚开始学习C / C ++,并被告知要使用delete删除单个对象并使用delete []来处理数组。

I just started learning C/C++ and I was told to use delete to delete a single object and to use delete [] for an array.

然后我找到了这个网站,它问了这个问题

Then I found this website which asks this question


此代码有什么问题吗?

Anything wrong with this code?

T *p = new T[10];
delete p;

注意:回复错误:不,一切正确,仅第一个
数组的元素将被删除,整个数组将被删除
,但仅第一个元素析构函数将被调用。

Note: Incorrect replies: "No, everything is correct", "Only the first element of the array will be deleted", "The entire array will be deleted, but only the first element destructor will be called".

这引发了一个问题,那段代码会发生什么?我本来会以为逻辑上是只有数组的第一个元素会被删除,但似乎没有。任何人都可以对此有所了解吗?

Which raises the question, what does happen in that block of code? I would have logically thought that it was "Only the first element of the array will be deleted" but it seems not. Can anyone shed some light on this?

推荐答案


  • 删除:这将释放由执行删除操作的指针当前分配的内存,它仅删除 所指向的内存。第一个变量。

    • delete: This frees the memory currently allocated by the pointer the delete is performed upon. It only deletes the memory pointed to by the first variable.

      delete []:这将释放为整个数组分配的内存。一个数组由多个变量组成-删除仅释放个内存分配给第一个变量,而delete []则完成全部操作。

      delete []: This frees the memory allocated for the whole array. An array consists of several variables - delete frees memory only allocated for the first variable, while delete [] does the whole thing.

      一个好方法想想它是在考虑将delete作为一条指令,而将delete []作为一个循环;在数组中循环遍历并分别对数组中的每个变量调用delete。这实际上不是这样的(实际工作有点

      A good way to think of it is considering delete as an instruction while delete [] as a loop; where the array is looped through and delete is called individually on each variable in the array. This is NOT how it works in reality (the real workings are a bit more complicated), but is a good way to understand the diff.

      析构函数称为在所有对象上,因为在某些情况下(例如在包含指针的对象数组的情况下),仅在第一个元素上调用析构函数并不会释放所有内存。

      The destructor is called on all objects, because in some cases such as in the case of an array of objects that contain pointers, calling the destructor on only the first element doesn't free all memory.

      这篇关于C / C ++删除与删除[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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