Wha*_*tIf -1 c++ object new-operator delete-operator
我正在尝试在堆上创建4个Student对象.当我尝试删除它们时,只删除第一个.
#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;
}
Run Code Online (Sandbox Code Playgroud)
这是输出:
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
Run Code Online (Sandbox Code Playgroud)
删除后:
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
Run Code Online (Sandbox Code Playgroud)
看起来好像只删除了第一个对象,但其余对象仍然存在.如何删除四个对象以避免内存泄漏?
当我尝试删除它们时,只删除第一个.
事实并非如此.Student事实上,你所有人都是delete.您可以通过Student在调用日志时向该日志添加一个析构函数来验证这一点- 您会看到它被调用4次.
误解来自删除实际意味着什么.删除并不意味着内存被清零 - 只是它可以用于将来使用.实际上将事情进展为零,这是浪费操作 - 所以通常不会发生这种情况.你正在做什么 - 从已删除的内存中读取数据 - 是未定义的行为.它看起来像以前的值,但它可能很容易为零.或随机垃圾.