为什么删除会忽略删除数组中除第一个对象之外的对象?

Why does delete ignore deleting objects in an arrary except the first one?

我正在尝试在堆上创建 4 个 Students 对象。当我试图删除它们时,只有第一个被删除。

#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

看起来好像只删除了第一个对象,但其余的仍然存在。如何删除这四个对象以避免内存泄漏?

When I attempt to delete them, only the first one is deleted.

事实并非如此。事实上,你所有的 Students 都是 deleted。您可以通过向 Student 添加一个析构函数来验证这一点,该析构函数在调用时进行记录 - 您会看到它被调用了 4 次。

误解来自删除的实际含义。删除并不意味着内存被清零——只是它可以供将来使用。实际继续进行并将事情归零是一种操作浪费 - 所以通常不会发生这种情况。您正在做的事情 - 从已删除的内存中读取数据 - 是 未定义的行为。它恰好看起来像以前的值,但它可能很容易为零。或随机垃圾。