我有管理 strAuthorisation
数组的 cAuthorisation
类
函数 resize
为下一条记录准备数组。
在 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) {}
请注意,目前的类违反了 the rule of three .
不确定这是否是一个学习练习,如果不是,请使用 std::vector<strAuthorisation>
. std::vector
将根据需要动态增长,并在超出范围时自动销毁。
关于c++ - 无法删除作为类字段的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11523356/