2016-02-28 93 views
-1

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

看起來好像只有第一個對象被刪除,但其餘的仍然存在。如何刪除四個對象以避免內存泄漏?

+0

此行'Student * temp = new Student();'應該是'Student * temp = new Student;' –

+0

如果您訪問已釋放的內存,它可能仍然包含與之前相同的數據;可能是沒有人在該內存中寫入其他數據。如果你想確保你沒有內存泄漏,用'valgrind'運行你的程序。 –

+0

試着將'Student * temp = new Student();'改成'Student * temp = new Student;'我仍然相同的輸出。 – WhatIf

回答

6

當我嘗試刪除它們時,只刪除第一個。

這是不正確的。實際上,您所有的Student都是delete d。你可以通過向Student添加一個析構函數來驗證這一點,該析構函數在被調用時記錄 - 你會看到它被調用4次。

這個誤解來源於實際刪除的意思。刪除並不意味着內存被清零 - 只是它可供將來使用。實際上繼續前進並將事情排除在外是浪費操作 - 通常不會發生。你在做什麼 - 從已刪除的內存讀取數據 - 是未定義的行爲。它看起來像以前的值,但它可能很容易爲零。或隨機垃圾。

+1

或Jon Skeet的測序基因組。 –

+0

@PreferenceBean我認爲這不適合我的機器的存儲。 – Barry

+0

然後,你必須有一臺非常舊的機器,因爲人類基因組需要大約1.5GB。或者我們說Jon Skeet不是人類......嗯...... –