如何在C++中按深度顺序销毁几个类
How to destruct a few classes in order of depth in C++
好吧,所以我把我的代码简化到最低限度,这样它就不会是一个很长的列表。。问题是,当我完成程序时,代码会崩溃,即调用析构函数。由于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()
中的逻辑显然是错误的。当您知道item
是NULL
时,您正在呼叫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)。您正在执行重复释放,这将导致未定义的行为。
相关文章:
- 为我的 c++ 类介绍制作一个三角形分类器.我有几个问题
- 使用 make 编译 MPI,几个命名空间错误,例如"错误:未知类型名称'使用'?
- 如何返回或护理项目清单基于几个类别
- 我们如何在文本文件中找到C++中的几个单词?
- 关于 std::bitset 构造函数的几个问题?
- 几个 Nt 函数在 Windows 7 x32 上返回STATUS_WAIT_0
- std::stoi 只转换前几个字符
- C++ 通过接口使用从其他几个类继承的类
- 在矢量中使用擦除时双重释放或损坏(快速顶部).如何擦除一个矢量的几个项目知道它们的索引?
- 如何遍历几个每小时一次的根(.root)文件,并将它们组合成更大的每日数据.root文件?
- 我有几个关于参考变量的问题
- 如何将几个变量复制到其他变量
- 如何在新设计中迁移需要几个额外参数的函数
- 如何按顺序迭代几个容器
- 为什么sleep in函数忽略了程序中的几个顺序指令
- 使用std::reverse来反转向量的前几个元素的顺序
- 如何强制按顺序调用几个函数
- 在几个顺序数组元素中输入相同的值
- 如何在C++中按深度顺序销毁几个类
- 关于评价顺序和比较的几个问题