2011-12-26 137 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