2012-02-13 95 views
0

這是關於這個指針上heap.Program如下分配對象的缺失,刪除這個指針

class Sample{ 
     private: 
       int m_value1; 
       int m_value2; 

     public: 
      Sample(); 
      void setValues(int m_value1, int m_value2); 
      void display(); 
     }; 

Sample::Sample(){ 
       this->m_value1 = 0; 
       this->m_value2 = 0; 
       } 

void Sample::setValues(int m_value1, int m_value2){ 
    this->m_value1= m_value1; 
    this->m_value2 = m_value2; 
    display(); 
    if(this != NULL) 
    { 
      cout <<"Deleting this pointer!"<<endl; 
      delete this; 
      cout <<"this->m_value1 is "<<this->m_value1<<endl; 
      cout <<"this->m_value2 is "<<this->m_value2<<endl; 

    } 
    } 

void Sample::display(){ 
    cout <<"Values are "<<this->m_value1<<" and "<<this->m_value2<<endl; 

    } 

int main(){ 
    Sample *obj1 = new Sample();; 
    obj1->setValues(4,6); 
    obj1->display(); 
    getch(); 
} 

OUTPUT:

Values are 4 and 6 
Deleting this pointer! 
this->m_value1 is 65535 
this->m_value2 is 6 
Values are 65535 and 6 

爲什麼價值爲m_value1消失,而它保持其他變量m_value2?

+0

[相關](http://stackoverflow.com/a/7039749/220636) – nabulke 2012-02-13 11:31:38

+0

也許你有學習'this'意義。所有的 – vulkanino 2012-02-13 11:32:36

+1

首先,'this'永遠不要向外界'NULL'非靜態成員函數內部時。其次,你應該**永遠不要刪除'this'!你在做什麼就像在拆下橋的時候拆掉它。 – 2012-02-13 11:33:11

回答

6

訪問成員變量delete this後是不確定的行爲 - 任何事情都有可能發生,包括讀取意外數據,程序崩潰或其他任何東西。該對象已被銷燬並解除分配,並嘗試解除引用無效指針。一旦delete this已經發生了 - 不要試圖訪問成員變量,不要試圖牛逼調用成員函數和don't do anything else (including comparing or casting) to this pointer

2

爲什麼m_value1的值消失,而它保持另一個變量m_value2?

您刪除後,您正在訪問的內存。這意味着你正在調用未定義的行爲。因此,任何事情都可能發生,你的觀察與其他事情一樣是對還是錯。

可能發生的情況是存儲m_value1的那部分內容被重用於其他內容,而m_value2的存儲尚未用於其他任何內容(尚)。

1

這是一個偶然的機會,可能是operator<<或刪除後的任何操作this分配足夠的內存來覆蓋一個而不是其他。

但是當你做一些不應該做的,你不應該依賴於任何特定的後果。

0

危險和不可預測的產出預計包括系統崩潰! 請勿直接刪除由此指向的位置。它不是一個好的編程習慣。刪除後不要使用內存。即使u必須把它放在一個斷言()內

this != NULL // this will never be NULL if used properly.