在C++中删除指针数组时析构函数崩溃

Noa*_*hai 0 c++ crash destructor delete-operator

我做了一个名为的课程cell.在这个类中有一个cell指针数组.标题看起来像这样:

class cell
{       
 public:
  cell();
  cell *c[8];
  void creatcells();
  virtual ~cell();
  ..

}
Run Code Online (Sandbox Code Playgroud)

并且cpp文件看起来像这样:

cell::cell()
{
//ctor
 for(int i=0;i<8;i++)
 {
   c[i]=NULL;
 }

}


void cell::creatcells()

 {
   cell c1,c2,c3,c4,c5,c6,c7,c8;

   c[0]=&c1;
   c[1]=&c2;
   c[2]=&c3;
   c[3]=&c4;
   c[4]=&c5;
   c[5]=&c6;
   c[6]=&c7;
   c[7]=&c8;
 }

cell::~cell()
{
    for(int i=0; i<8; i++)
    {
        if (c[i]!=NULL)
        {
                    delete c[i];
        }
    }
    delete[] c;

 }
Run Code Online (Sandbox Code Playgroud)

但每次程序结束时,都会崩溃,为什么?
我试过没有if (c[i]!=NULL),但这没有帮助.只有没有for循环,代码才能完美结束,但我知道这也必须删除.我想我正确地写了析构函数,不是吗?

Gau*_*gal 5

void cell::creatcells()
 {
   cell c1,c2,c3,c4,c5,c6,c7,c8;

   c[0]=&c1;
   c[1]=&c2;
   ...
Run Code Online (Sandbox Code Playgroud)

所有上述cell对象都会在结尾处自动销毁createcells().因此delete c[i];析构函数中的UB就是UB.你想要的是什么

 c[0]= new cell();
 c[1]= new cell();
Run Code Online (Sandbox Code Playgroud)

  • 您真正需要的是`std :: vector <cell>`并返回值优化! (3认同)