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
并没有调用~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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您尚未结束该行,因此该行未输出。添加<代码><< endl 到您的打印。
You haven't ended the line, so the line was not output. Add
<< endl
to your printing.