关于Struct上的new和delete操作符

about new and delete operators over Struct

本文关键字:delete 操作符 new Struct 上的 关于      更新时间:2023-10-16

我有一个struct

#ifndef EVENT_H
#define EVENT_H
struct Event {
int ID;
int num;
int * energies;
};
#endif

和一个与Event结构

一起工作的函数
#include <fstream>
#include "Event.h"
#include <iostream>
using namespace std;
Event * read(std::ifstream& os, Event * ev)
{
if(os.fail()) return NULL;
os >> ev->ID >> ev->num;
ev->energies = new int[ev->num];
if(ev->ID!=0 && ev->num!=0){
for (int i = 0; i < ev->num; ++i)
{
os >> * (ev->energies+i);
}
}   
return ev;
}

这是main。cpp

#include <iostream>
#include <fstream>
#include "Event.h"
using namespace std;
Event * read(ifstream& os, Event * ev);
void dump(const Event& ev);
void clear(Event * ev);
int main(int argc, char const *argv[])
{
ifstream os(argv[1]);
Event * ev = new Event;
cout << "Created " << ev << endl;
Event * pointer=read(os, ev);
while(pointer!=NULL)
{
dump(*ev);
clear(ev);
Event * ev = new Event;
pointer = read(os,ev);
}
return 0;
}

我的问题是:为什么在这种情况下,在read()函数的每次调用结束时,不释放内存(在read()中与ev->energies = new int[ev->num];分配)?

不,内存没有被释放。在函数的末尾,您需要调用

delete [] ev->energies

您的印象是,当分配的指针超出作用域时将被删除。这不是真的。它会泄漏内存。这个例子将突出显示你在注释中给出的代码中遗漏的内容:

#include <iostream>
using namespace std;
int* read(int *array)     {
        int i=0;
        int num=200;
        array = new int[num];
        cout << "Newly allocated pointer " << array << endl;
        if(num==0) return NULL;
        while(i<num) {
                array[i] = i*i;
                i++;
        }
        return array;
}
int main(int argc, char const *argv[])
{
  int *ptr;
  cout << "Original pointer address " << ptr << endl;
  int *n = read(ptr);
  cout << "Last value in allocated pointer " << n[199] << endl;
  cout << "Allocated pointer address " << n << endl;
  cout << "Original pointer address " << ptr << endl;
  // following line can cause a segmentation fault
  // cout << "Last value in original pointer (actually garbage) " << ptr[199] << endl;
  delete[] n; // really should delete it
}

read()中的*数组是按值传递的,所以改变它将是局部作用域