【发布时间】:2016-02-28 17:06:37
【问题描述】:
我正在尝试在堆上创建 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;` 我仍然得到相同的输出。
-
@EdHeal 这些在这里完全相同。
-
@CodyGray:在这种情况下你不能使用
delete[],因为数组没有被分配new[]。
标签: c++ object new-operator delete-operator