如何在C++中按深度顺序销毁几个类

How to destruct a few classes in order of depth in C++

本文关键字:几个 顺序 C++ 深度      更新时间:2023-10-16

好吧,所以我把我的代码简化到最低限度,这样它就不会是一个很长的列表。。问题是,当我完成程序时,代码会崩溃,即调用析构函数。由于point类在ptlist类中,而board类中的ptlist我认为在删除析构函数中的对象时我必须进行一些how链接,但在我到达ptlist的析构函数的if(item!=NULL)行后它崩溃了。。。由于某种原因,它既没有输入if子句,也没有输入else子句。。不知道为什么。。无论如何,这是我的程序的精简代码:

[EDIT]感谢大家,我修复了代码,现在它运行得很完美。感谢所有

#include <windows.h>  //include all the basics
#include <tchar.h>    //string and other mapping macros
#include <string>
#include <ctime>
#include <stdlib.h>
#include <algorithm>
#include <iostream>
using namespace std;
class point
{
    unsigned x;
    unsigned y;
    int id;
    int type;
    bool covered;
    int maze;
public:
    point(){x = 0; y = 0; id = 0; type = -1; covered = true; maze = 0;}
    ~point(){x = 0; y = 0; id = 0; type = 0; covered = true; maze = 0;}
};
class ptlist
{
    point ** item;
    int length;
    int itemmax;
public:
    ptlist(){item = NULL; length = 0; itemmax = 0;}
    ptlist(int imax);
    ~ptlist();
};
ptlist::ptlist(int imax)
{
    item = new point *[imax];
    length = 0;
    itemmax = imax;
}
ptlist::~ptlist()
{
    delete [] item;
}
class board
{
    ptlist *wall;
    ptlist *path;
public:
    board(){wall = new ptlist(1); path = new ptlist(1);}
    ~board(){delete wall; delete path;}
};

~ptlist()中的逻辑显然是错误的。当您知道itemNULL时,您正在呼叫delete item。您应该删除else子句。

此外,ptlist(int max)的构造函数从不为每个指针创建点数组。

您在不应该使用delete[]的地方。

wall = new ptlist(1);
delete wall; // NOT delete [] wall

path相同。

规则是,当您分配一个数组(使用new [])时,您将使用delete[]解除分配。当您使用new进行分配时,您将使用delete进行解除分配。

此外,您正在创建指向点的指针数组或指向点的数组。无论如何,您永远不会初始化这些指针,而是稍后delete它们。您至少应该在构造函数中将它们初始化为NULL

ptlist::ptlist(int imax)
{
    item = new point *[imax];
    for( int i = 0; i<imax; ++i )
        item[i] = NULL;
    length = 0;
    itemmax = imax;
}

如果它们是数组而不是单独的点,则应该在析构函数中使用delete []删除它们。

除了混淆delete和delete[]之外,您不需要循环删除new[]分配的数组的所有元素。操作员删除[]可为您执行此操作。参见#5.3.5(6)。您正在执行重复释放,这将导致未定义的行为。