C++ can';t删除属于类字段的数组
我有一个类C++ can';t删除属于类字段的数组,c++,C++,我有一个类cauthorization,它管理strauthorization 函数resize为下一条记录准备就绪 在调整大小期间,在线删除[]数据我崩溃了 struct strAuthorisation { double Amount; }Authorisation; class cAuthorisation { public: int size; strAuthorisation *data; cAuthorisation () { size=0;
cauthorization
,它管理strauthorization
函数resize
为下一条记录准备就绪
在调整大小期间
,在线删除[]数据代码>我崩溃了
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;
为什么不能删除类数组?它会崩溃,因为数据
是一个统一的指针<空指针上的代码>删除[]
是安全的(无操作),因此在构造函数中初始化数据
:
cAuthorisation() : size(0), data(0) {}
请注意,当前的类正在违反
不确定这是否是学习练习,如果不是使用
std::vector
。将根据需要动态增长,并在超出范围时自动销毁。您尚未初始化数据
指针。所以你在做这样的事情:
Foo *data;
delete [] data;
“数据”是一个指针,其值从未初始化过。您还应该在添加
时检查是否需要调整大小,而不是每次调整大小。你在resize
中有内存泄漏,你没有删除a
我强烈地想提到std::vector
。resize中a
的目的是什么?