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

发布于 2024-12-23 00:56:20 字数 1016 浏览 1 评论 0原文

我有一堂课:

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 " << 的字符串宽度<< “通过”<<高度<< “矩形。” 但我没有....

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

I have a class:

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;     
}

This is a quite simple C++ sample. I compiled in Linux g++ and run it.
Suddenly I found the delete p did not call ~Rectangle() ...
I should see string like "Destructing " << width << " by " << height << " rectangle."
but I did not ....

but why?
Deleting an object should call that object's destructor, shouldn't it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

_畞蕅 2024-12-30 00:56:20

您尚未结束该行,因此该行未输出。添加<代码><< endl 到您的打印。

You haven't ended the line, so the line was not output. Add << endl to your printing.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文