2011-12-26 125 views
-3

我有一個類:C++析構函數沒有被調用?

class Rectangle { 
    int width; 
    int height; 
public: 
    Rectangle(int w, int h) { 
     width = w; 
     height = h; 
     cout << "Constructing " << width << " by " << height << " rectangle.\n"; 
    } 

    ~Rectangle() { 
     cout << "Destructing " << width << " by " << height << " rectangle.\n"; 
     } 
    int area() { 
      return width * height; 
    } 
}; 


int main() 
{ 
    Rectangle *p; 

    try { 
     p = new Rectangle(10, 8); 
    } catch (bad_alloc xa) { 
     cout << "Allocation Failure\n"; 
     return 1; 
    } 

    cout << "Area is " << p->area(); 

    delete p; 

    return 0;  
} 

這是一個相當簡單的C++樣品。我在Linux g ++中編譯並運行它。 突然我發現delete p沒叫〜矩形()... 我應該看到串像"Destructing " << width << " by " << height << " rectangle." 但我沒有....

但爲什麼呢? 刪除一個對象應該調用該對象的析構函數,不是嗎?

+0

你可以發佈你的析構函數的代碼和實際調用它的代碼片段嗎? – 2011-12-26 07:41:29

+0

調用'delete'之前打印的最後一條消息不會以換行符結束。機會是析構函數消息結束連接到「區域是80」,你可能錯過了它。 – 2011-12-26 07:42:07

+3

[It does](http://ideone.com/2fTkV)向我們展示代碼**您**編譯並運行。 – 2011-12-26 07:42:48

回答

1

您還沒有結束該行,因此該行未輸出。將<< endl添加到您的打印中。

+0

YE ...我真是個傻瓜... – barfatchen 2011-12-26 07:52:50

+0

好奇。爲什麼當程序退出時不會刷新緩衝區? – sharptooth 2011-12-26 08:02:15

+0

構造10乘8矩形。面積是80×10×8矩形。他們合併成一條線,我錯過了! – barfatchen 2011-12-26 08:04:28