c ++析构函数没被调用?

时间:2011-12-26 07:37:44

标签: c++ destructor

我有一个班级:

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没有调用~Rectangle()...... 我应该看到像"Destructing " << width << " by " << height << " rectangle."这样的字符串 但我没有......

但为什么呢? 删除一个对象应该调用该对象的析构函数,不应该吗?

1 个答案:

答案 0 :(得分:1)

您尚未结束该行,因此未输出该行。在打印中添加<< endl

相关问题