无法删除属于类字段的数组
can't delete array that is class field
我有一个类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"是一个值从未初始化的指针。
相关文章:
- 将位字段导出到数组
- 结构字段名称与 GDB 中的 STL 数组冲突
- 结构数组中所有类似字段的总和
- 如何使用函数的输出初始化 const 数组结构字段?
- 如何使用连接器 c++ 在 mySQL 表二进制(16) 字段中存储 c++ 字节数组?
- 在类中定义数组的方法和字段
- 获取类中的字段数
- 指向结构中的数组的指针,其中每个字段都是一个动态数组
- 在C++中使用 RapidJSON 访问 JSON 数组的字段
- 无法从JNI设置Java Int数组字段
- 将具有不同字段的结构转换为 uint8 的数组
- 将指向结构的指针转换为具有较少字段数的另一种结构类型
- 如何使用指向该数组的指针访问结构数组中包含的结构中的字段?[C++]
- 是否可以使用位字段数组
- 删除内存字段(数组)中的单个字节
- 指向函数中structs元素字段数组的指针
- 编译时开关生成基于结构中的字段数
- 我如何让一个输入语句重复,直到用户选择的字段数完成
- (C++)动态分配的井字游戏数组
- 井字棋数组字符错误