无法删除属于类字段的数组

can't delete array that is class field

本文关键字:字段 数组 属于 删除      更新时间:2023-10-16

我有一个类cAuthorisation,它管理strAuthorisation的数组函数CCD_ 3为下一个记录准备aray。

resize期间,在delete [] data;线路上,我发生了故障。

struct strAuthorisation 
{ 
double Amount; 
}Authorisation;
class cAuthorisation { 
public: 
    int size; 
    strAuthorisation *data; 
cAuthorisation ()
{
    size=0;
}
~cAuthorisation()
{
};
void Add(strAuthorisation )
{
    resize();
    data[size]=*value;
}
void resize() 
{
    strAuthorisation *a = new strAuthorisation[5];
    size_t newSize = size + 1 ;
    strAuthorisation *newArr = new strAuthorisation[newSize];
    memcpy( newArr, data, size * sizeof(strAuthorisation) );
    size = newSize;
    delete [] data;
    data = newArr;
}
} Authorisations;

为什么不能删除类数组?

它崩溃是因为data是一个统一的指针。空指针上的delete[]是安全的(无操作),因此在构造函数中初始化data

cAuthorisation() : size(0), data(0) {}

请注意,目前的类违反了三规则。

不确定这是否是一个学习练习,如果不是使用std::vector<strAuthorisation>std::vector将根据需要动态增长,并在超出范围时自动销毁。

您尚未初始化data指针。所以你正在制作这样的东西:

Foo *data;
delete [] data;

"data"是一个值从未初始化的指针。