关于Struct上的new和delete操作符
about new and delete operators over Struct
我有一个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()中的*数组是按值传递的,所以改变它将是局部作用域
相关文章:
- 如果操作符delete没有实现,为什么不编译它
- 提升ipc new和delete操作符
- 当delete操作符释放内存时,我为什么需要析构函数
- 当操作符delete()在汇编中删除vptr指针时
- 为特定类重写new和delete操作符的原因是什么?
- 使用delete操作符删除void指针
- 关于操作符new()和操作符delete()的问题
- c++是delete操作符重写内存
- New和delete操作符不影响指向该类的指针的Deque的内容
- 涉及数组指针时delete[]操作符的问题
- 当构造函数抛出异常时,Delete操作符出现分段错误
- delete[]操作符是否适用于通过指针返回的动态分配的内存?
- 如何重载操作符new和delete来跟踪内存
- 何时调用delete操作符
- 为什么要替换默认的new和delete操作符
- 重载new和delete操作符
- c++的new和delete操作符重载
- 编译不带delete操作符的c++
- 关于Struct上的new和delete操作符
- 动态分配LPTSTR (TCHAR*)和delete[]操作符的不稳定行为