我一直在刷我的C++,我有一个关于删除新内存的快速问题.正如您在下面看到的,我有一个包含FileData*列表的简单类.我创建了一个数组来保存要推送到列表中的FileData对象.当ReportData被破坏时,我遍历列表并删除每个元素.我的问题是,当我使用reportData时,如何删除数组,以便我没有任何内存泄漏?
class REPORTAPI ReportData {
public:
ReportData()
{
}
virtual ~ReportData()
{
printf("Starting ReportData Delete\n");
for (list<FileData*>::iterator i = ReportFileData.begin(), e = ReportFileData.end(); i != e; )
{
list<FileData*>::iterator tmp(i++);
delete *tmp;
ReportFileData.erase(tmp);
}
for (list<SupressionData*>::iterator i = ReportSupressionData.begin(), e = ReportSupressionData.end(); i != e; )
{
list<SupressionData*>::iterator tmp(i++);
delete *tmp;
ReportSupressionData.erase(tmp);
}
ReportFileData.clear();
ReportSupressionData.clear();
printf("Finished ReportData Delete\n");
}
list<FileData *> ReportFileData;
list<SupressionData *> ReportSupressionData;
}
extern "C" __declspec(dllexport) FileData* __stdcall createFileData(string fileName, long recordCount, long addPageCount)
{
return new FileData(fileName, recordCount, addPageCount);
}
Run Code Online (Sandbox Code Playgroud)
ReportData *reportData = createrd();
if (reportData != NULL)
{
CreateFileDataFunc createfd (reinterpret_cast<CreateFileDataFunc>(GetProcAddress (dll, "createFileData")));
const int num_files = 5;
FileData *fileData[num_files];
char buff[256] = {'\0'};
for (int i = 0; i < num_files; i++)
{
sprintf(buff, "test: %d", i);
fileData[i] = createfd(buff, 1, 1);
reportData->ReportFileData.push_back(fileData[i]);
}
delete reportData;
reportData = NULL;
delete [] fileData; // this is throwing an access violation error:
//EAccessViolation: 'Access violation at address 326025AF. Write of address 00000008'.
}
Run Code Online (Sandbox Code Playgroud)
---我从ReportData dtor中删除了删除操作,现在我正在循环和删除:
for(int i = 0; i < num_files; i++)
{
delete fileData[i];
}
Run Code Online (Sandbox Code Playgroud)
这更容易理解,然后必须依靠单独的对象的dtor来清理内存.
你没有.fileData是一个自动(堆栈)变量.您没有使用new分配它,因此不要删除它.
[编辑:我也不确定,但我认为你可能会遇到从main.cpp删除那些FileData对象的问题,考虑到它们是在某些dll中分配的.dll是否提供了删除功能?]