我正試圖在堆上創建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