我正试图在堆上创建4个学生对象。当我试图删除它们时,只有第一个被删除。为什么删除忽略删除除第一个以外的任何对象?
#include <iostream>
using namespace std;
class Student{
private:
int ID;
int score;
public:
void setID(int num);
int getID();
void setScore(int num);
int getScore();
};
void Student::setID(int num)
{
ID = num;
}
int Student::getID()
{
return ID;
}
void Student::setScore(int num)
{
score = num;
}
int Student::getScore()
{
return score;
}
class Creator
{
public:
static int nextID;
Student* getObject();
};
int Creator::nextID = 0;
Student* Creator::getObject()
{
Creator::nextID++;
Student* temp = new Student();
temp->setID(Creator::nextID);
return temp;
}
int main()
{
Creator maker;
Student *pupil[4];
int mark = 70;
for(std::size_t i = 0; i < (sizeof(pupil)/sizeof(pupil[0])); i++)
{
pupil[i] = maker.getObject();
pupil[i]->setScore(mark);
mark += 10;
}
for(std::size_t i = 0; i < (sizeof(pupil)/sizeof(pupil[0])); i++)
{
cout<< "Sudent ID: "<<pupil[i]->getID()<<" has score of: "<<pupil[i]->getScore()<<endl;
}
//attempting to delete
for(std::size_t i = 0; i < (sizeof(pupil)/sizeof(pupil[0])); i++)
{
delete pupil[i];
}
//confirm deletion
for(std::size_t i = 0; i < (sizeof(pupil)/sizeof(pupil[0])); i++)
{
cout<< "Sudent ID: "<<pupil[i]->getID()<<" has score of: "<<pupil[i]->getScore()<<endl;
}
return 0;
}
这里是输出:
Sudent ID: 1 has score of: 70
Sudent ID: 2 has score of: 80
Sudent ID: 3 has score of: 90
Sudent ID: 4 has score of: 100
删除后:
Sudent ID: 7864516 has score of: 7864516
Sudent ID: 2 has score of: 80
Sudent ID: 3 has score of: 90
Sudent ID: 4 has score of: 100
看起来好像只有第一个对象被删除,但其余的仍然存在。如何删除四个对象以避免内存泄漏?
此行'Student * temp = new Student();'应该是'Student * temp = new Student;' –
如果您访问已释放的内存,它可能仍然包含与之前相同的数据;可能是没有人在该内存中写入其他数据。如果你想确保你没有内存泄漏,用'valgrind'运行你的程序。 –
试着将'Student * temp = new Student();'改成'Student * temp = new Student;'我仍然相同的输出。 – WhatIf