c++ - 无法删除作为类字段的数组

标签 c++

我有管理 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/

相关文章:

c++ - Haskell Thrift 库在性能测试中比 C++ 慢 300 倍

c++ - Boost Lambda/Phoenix - 如何做返回另一个 lambda 的 lambda?

c++ - 尝试将 std::sort() 与自定义对象一起使用

c++ - 无法使用删除 "pointer being freed was not allocated"

c++ - 如何根据先前的行为预测系统的行为

c++ - 使用 std::map 作为关联数组

c++ - 指针上的算术是关联的吗?

c++ - 在函数尾声混淆之前堆栈必须是干净的

c++ - 未调用移动构造函数

c++ - float 减法问题