我有一個類: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."
但我沒有....
但爲什麼呢? 刪除一個對象應該調用該對象的析構函數,不是嗎?
你可以發佈你的析構函數的代碼和實際調用它的代碼片段嗎? – 2011-12-26 07:41:29
調用'delete'之前打印的最後一條消息不會以換行符結束。機會是析構函數消息結束連接到「區域是80」,你可能錯過了它。 – 2011-12-26 07:42:07
[It does](http://ideone.com/2fTkV)向我們展示代碼**您**編譯並運行。 – 2011-12-26 07:42:48