[英]How to properly deallocate memory for a 2d array in C++?
Here's how I allocate it: 这是我的分配方式:
float** matrix = new float*[size];
for (int i = 0; i < size; i++) {
matrix[i] = new float[size];
}
And here's how I deallocate: 这是我解除分配的方式:
if (matrix != nullptr) {
for (int i = 0; i < size; i++) {
delete[] matrix[i];
}
}
free(matrix);
Is this correct or should I also delete[]
the outer array? 这是正确的还是我也应该delete[]
外部数组?
delete[]
is always paired with a new[]
. delete[]
总是与new[]
配对。
delete
is always paired with a new
. delete
总是与new
配对。
So yes, in your case, you need to call delete[] matrix;
所以是的,在您的情况下,您需要调用delete[] matrix;
to release the array of float*
pointers. 释放float*
指针数组。 Don't use free
unless that pointer has been obtained with a call to malloc
&c., which would be unusual in C++. 除非已经通过调用malloc
&c。获得了该指针,否则不要使用free
,这在C ++中是不常见的。
Although, if you want to model a matrix in the mathematical sense then might I suggest you use a 3rd partly library. 虽然,如果您想在数学意义上对矩阵建模,那么我建议您使用第3部分库。 I use BLAS, part of the Boost distribution. 我使用BLAS,它是Boost发行版的一部分。
How to properly deallocate memory for a 2d array in C++? 如何在C ++中为2D数组正确地释放内存?
Not manually. 不手动。 Use an abstraction like std::vector
that deallocates memory for you thanks to RAII , or std::array
if you know the size of your matrix at compile-time. 使用RAD或std::array
类的抽象,如std::vector
,如果您知道编译时矩阵的大小,则可以使用std::array
。
{
std::vector<std::vector<float>> matrix(size);
for(auto& v : matrix) v.resize(size);
}
// memory automatically freed at the end of the scope
You should almost never use new
and delete
in Modern C++. 在Modern C ++中, 几乎永远不要使用new
和delete
。 Refer to my answer here for more information: Malloc vs New for Primitives 有关更多信息,请参见我的答案: Malloc与原始函数的新增功能
If you are writing a program that requires an high-performance matrix implementation, please do not create your own. 如果要编写需要高性能矩阵实现的程序,请不要创建自己的程序。 Your code and my example using std::vector
both have a cache-unfriendly jagged layout which can severely harm performance. 您的代码和我的使用std::vector
示例都具有对缓存不友好的锯齿状布局,这会严重损害性能。 Consider using an high-quality production-ready library such as Eigen, Blaze, or BLAS instead. 考虑使用高质量的生产就绪库,例如Eigen,Blaze或BLAS。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.