简体   繁体   English

在C ++中取消分配多维数组

[英]Deallocate multidimensional array in c++

How would I go about destroying a dynamic array of arbitrary size, dimensions, and type? 我将如何销毁任意大小,尺寸和类型的动态数组? Will delete[] automatically go down the levels of a two dimensional array or just delete the first level of pointers so the program need to manually iterate over each array level? 是否delete []会自动下降到二维数组的级别或仅删除第一级指针,以便程序需要在每个数组级别上手动进行迭代?

Ideally I need a single command (for use in a template class) that will destroy one to four dimensional arrays. 理想情况下,我需要一个命令(用于模板类),该命令将销毁一到四个维数组。 It would also work if there is a way to check the number of dimensions of an array. 如果有一种方法可以检查数组的维数,那么它也将起作用。

I am using dymanic arrays such as double* ar = new double[100]; 我正在使用动态数组,例如double * ar = new double [100];

如果您使用的是C ++,请使用std::vectorstd::unique_ptr

You need to manually iterate over all levels to delete them. 您需要手动遍历所有级别以将其删除。
If there is a way to check the dimensions, you can just use that to select the correct destruction process. 如果可以检查尺寸,则可以使用该方法选择正确的销毁过程。

Also, why not use vectors ? 另外,为什么不使用向量呢? they are fast and are automatically deallocated when out of scope 它们速度很快,超出范围时会自动释放

if you instanciate the 2 dimensional array like new int[10][20] the delete[] will destroy all the array, but if you created it iterating like myarray[i] = new int[20] so you will have to iterate again to destroy each dimension. 如果像new int[10][20]那样实例化二维数组,则delete[]将破坏所有数组,但是如果创建时像myarray[i] = new int[20]那样迭代,那么您将不得不再次迭代破坏每个维度。

If you are not sure about how to destroy the array I would recoment you to use the STL vector. 如果您不确定如何销毁数组,建议您使用STL向量。

Basically 1 new = 1 delete and 10 new = 10 delete , so you have to delete everything you allocate, the number of those operation called should be equal. 基本上1 new = 1 delete10 new = 10 delete ,所以您必须删除分配的所有内容,被调用的那些操作的数量应相等。

There's no way of knowing (from compilers/programs point of view) what's the real data pointer, what's just some trash or what is referenced elsewhere (and will be used) and so on. (从编译器/程序的角度来看)无法知道什么是真正的数据指针,什么只是垃圾或在其他地方引用(并将使用)等等。

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

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