简体   繁体   English

取消分配数组的不同方法-C ++

[英]Different ways to deallocate an array - c++

If you have said 如果你说过

int *arr = new int[5];

What is the difference between 之间有什么区别

delete arr;

and

delete [] arr;

I ask this because I was trying to deallocate memory of a 2d array and 我问这是因为我试图释放2d数组的内存,并且

delete [][] arr; 

did not seem to work but 似乎没有用,但是

delete arr;

seemed to work fine 似乎工作正常

Thank you in advance! 先感谢您!

If you have said 如果你说过

 int arr[5]; 

What is the difference between 之间有什么区别

 delete arr; 

and

 delete [] arr; 

One has an extra pair of brackets in it. 一个里面有一对额外的括号。 Both will probably crash and/or corrupt the heap. 两者都可能崩溃和/或破坏堆。 This is because arr is a local variable which can't be delete d - delete only works on things allocated with new . 这是因为arr是不能delete的局部变量d- delete仅对分配有new东西有效。

delete [][] arr; is not valid syntax. 是无效的语法。 For an array allocated with for example new int[2][2] , use delete [] . 对于分配了例如new int[2][2]的数组,请使用delete []

Neither of the delete's is correct. 删除均不正确。

When you declare an array like this: 当您声明这样的数组时:

int arr[5];

The space is allocated on the stack . 该空间在stack上分配。 Memory allocated on the stack isn't cleaned by delete. 堆栈中分配的内存不会通过删除清除。 It gets auto cleaned (Although clean is not the correct term technically) when the stack unrolls on exit of scope. 当堆栈在作用域退出时展开时,它会自动清理(尽管从技术上讲,清理不是正确的术语)。 (Check When is an object "out of scope"? ) (检查对象何时“超出范围”?

If you declre your array like this: 如果您像这样对数组进行修饰:

int *arr = new int[5]; // new allocates memory on heap

You call 你打电话

delete[] arr; // this takes care of cleaning up memmory on **heap**

new type requires delete new type需要delete
new type[size] requires delete [] new type[size]需要delete []
Using one instead of the other is wrong. 用一个代替另一个是错误的。

Btw you should not use such raw pointers like this unless you have a very good reason. 顺便说一句,除非您有充分的理由,否则不应使用此类原始指针。 Use std::vector or std::array instead. 使用std::vectorstd::array代替。

And 2D M x N arrays should generally be linearised into 1D M*N arrays, also using these containers. 并且通常也应使用这些容器将2D M x N阵列线性化为1D M*N阵列。

I assume you mean new int[5] , and the same new for dynamic memory. 我假设你的意思是new int[5]和相同的new动态内存。 Otherwise, you are using stack, not the heap, and delete is undefined 否则,您使用的是堆栈,而不是堆,并且delete是未定义的

While delete arr may seem to work for a 2-d array, I believe that the standard requires the following: 尽管delete arr似乎适用于delete arr数组,但我认为该标准要求以下条件:

delete [] arr
arr=nullptr

This is because memory allocated with new [] must be freed with delete [] and vice versa. 这是因为用new []分配的内存必须用delete []释放,反之亦然。 Also, it is dangerous to leave dangling pointers, hence the final line 另外,留下悬空的指针很危险,因此最后一行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM