【发布时间】:2016-05-27 21:23:47
【问题描述】:
我是析构函数的新手,到目前为止,我一直遵循的教程已经很清楚了。调用析构函数时实际发生了什么?为什么我仍然从被破坏的对象中获取值?
class Box {
public:
Box(double l = 2.0, double b = 2.0, double h = 2.0) { //Constructor
cout << "Box Created" << endl;
length = l;
breadth = b;
height = h;
}
~Box() {
cout << "Box Destroyed" << endl; // Box Destructor
}
double volume() {
return length*breadth*height;
}
private:
double height;
double breadth;
double length;
};
void main() {
Box Box1(10, 15, 5); //Constructors used
Box Box2(5, 15, 20);
cout << "Box1.volume: " << Box1.volume() << endl;
cout << "Box2.volume: " << Box2.volume() << endl;
Box1.~Box(); //Destructors called
Box2.~Box();
cout << "Box1.volume after destruction: " << Box1.volume() << endl;
cout << "Box2.volume after destruction: " << Box2.volume() << endl;
}
【问题讨论】:
-
您不想显式调用析构函数。由于您的对象是在堆栈上分配的,因此当您的函数返回时,将自动调用析构函数。
-
@RJM 并非所有对象都在堆栈上创建,但您的观点仍然有效。
-
你几乎不应该显式调用析构函数,这里的 box1 和 2 是自动变量,在这种情况下,当作用域离开 bloc 时会调用析构函数。
-
@PW。 s/几乎没有/几乎没有
-
@Marcus Muller - 当然它们并没有全部分配在堆栈上。这就是为什么我通过指出 OP 对象是在堆栈上分配的来限定我的评论的原因。 :-)
标签: c++ destructor