C++ 如何删除这个二维指针数组?制作析构函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9647776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:07:22  来源:igfitidea点击:

How to delete this 2-dimensional array of pointers? Making a destructor

c++arrayspointersdelete-operator

提问by freinn

malla = new Celula**[n + 2];  
for(int i = 0 ; i < n + 2 ; ++i){  
     malla[i] = new Celula*[m + 2];
     for(int j = 0 ; j < m + 2 ; ++j){
         malla[i][j] = new Celula[m];
     }
}

I'm making this code and I allocate memory like this (I want a n*marray of pointers to Celula, is okay? Now I need a destructor.

我正在编写这段代码并像这样分配内存(我想要一个n*m指向 Celula 的指针数组,可以吗?现在我需要一个析构函数。

Now I don't know how to access to an object in this array and:

现在我不知道如何访问这个数组中的对象,并且:

malla[i][j].setestado(true);

doesn't work.

不起作用。

回答by Konrad Rudolph

Don't use pointers.

不要使用指针

std::vector<std::vector<Celula> > malla(n, std::vector<Celula>(m));

// …
malla[1][2].setestado(true);

Upshot: one line instead of seven, easier usage, no deleteneeded anywhere.

结果:一行而不是七行,更容易使用,任何delete地方都不需要。

As an aside, it's conventional to use English identifiers in code. If nothing else, this has the advantage that people can help you better if they don't speak the same language as you.

顺便说一句,在代码中使用英文标识符是惯例。如果不出意外,这样做的好处是,如果人们与您说不同的语言,他们可以更好地帮助您。

回答by Mr.Anubis

Seriously consider the advice of @konrad's . If anyhow you want to go with raw array's , you can do :

认真考虑@konrad 的建议。如果无论如何你想使用原始数组,你可以这样做:

To deallocate :

解除分配:

 for(int i = 0 ; i < n + 2 ; ++i)
 {
 for(int j = 0 ; j < m + 2 ; ++j) delete[] malla[i][j] ;
 delete[] malla[i];
 }
 delete[] malla;

To access the object :

访问对象:

 malla[i][j][_m].setestado(true);

Edit :

编辑 :

if malla[i][j]is pointer to simply object then destructor/deallocation will look like :

如果malla[i][j]是指向简单对象的指针,则析构函数/解除分配将如下所示:

 for(int i = 0 ; i < n + 2 ; ++i)
 {
 for(int j = 0 ; j < m + 2 ; ++j) delete malla[i][j] ;
 delete[] malla[i];
 }
 delete[] malla;

Access object/member can be done like : (*malla[i][j]).setestado(true);or malla[i][j]->setestado(true);

访问对象/成员可以这样做:(*malla[i][j]).setestado(true);malla[i][j]->setestado(true);