我有一个类: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